# -*- coding: UTF-8 -*-

from datetime import datetime
import time
import requests
from datetime import timedelta
from lxml import html

import json
from gm_rpcd.all import RPCDFaultException
from gm_types.error import ERROR
from gm_types.mimas.enum import MEDIA_IMAGE_URL_SOURCE, IMAGE_TYPE
from gm_types.mimas.qa import GRABBING_PLATFORM, QA_CONTENT_TYPE, VIDEO_SOURCE_TYPE
from gm_types import user_hierarchy
from gm_types.doctor import HOSPITAL_LEVEL, DOCTOR_TITLE_TYPE
from gm_types.gaia import HOSPITAL_TYPE, DOCTOR_TYPE
from gm_types.gaia import USER_CLASSIFY
from django.db.models import Q
from django.db import transaction
from django.conf import settings
from django.utils.dateparse import parse_datetime
from requests import Response

from live.tasks import get_qiniu_persistent_ids

from gm_dataquery.client import rpc
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from gm_dataquery.dict_mixin import to_dict
from gm_types.antispam import DocType
from gm_types.mimas.qa import GRABBING_PLATFORM, CONTENT_CLASS
from user_hierarchy.manager.event_dispatcher import EventDispatcher
from qa.models import Answer, AnswerImage, AnswerReply, SendAnswer
from qa.models import Question, QuestionTag, QuestionImage, BDAnswer
from qa.models import AnswerTop, AnswerVote, BDAnswer
from qa.models import KolAnswer, KolQuestion
from qa.models import BDAnswer

from utils.common import get_data_from_rich_text
from utils.rpc import rpc_client
from utils.push import special_push_limit
from user_hierarchy.portal import process_task
from qa.libs import get_media_extra_info
from qa.tasks.answer import add_fake_vote_to_answer, send_answer_on_time, push_to_question_provider
from qa.tasks.view import gif_create_webp
from qa.views.answer import notify_recommended_user
from qa.utils.image import handle_image_type
from talos.portal import get_doctor_by_user_id
from qa.tasks.answer import comment_push
from talos.services.user import UserService
from talos.models.doctor import DoctorMessageList


def deal_EventDispatcher(obj, EventType, is_recommend=False, type='create'):
    if (type == 'update' and is_recommend and not obj.is_recommend) or (type == 'create' and obj.is_recommend):
        process_task(user_id=obj.user_id, event_type=EventType, related_item=obj.id)

def antispam_feedback(item_queryset, doc_type):
    docs = [{
        'doc_id': x.id,
        'spam': bool(x.spam_label),
        'content': x.content,
        'doc_type': doc_type
    } for x in item_queryset]
    try:
        rpc_client['antispam/feedback/batch'](docs=docs).unwrap()
    except:
        pass


def qa_content_type_judge(richtext):
    """
    问答 内容类型判断。默认内容为富文本
    :param richtext:
    :return:
    """
    content_type = QA_CONTENT_TYPE.ORDINARY

    if not richtext:
        return content_type

    element_obj = html.fromstring(richtext)
    if bool(element_obj.xpath("//video[1]")):
        content_type = QA_CONTENT_TYPE.VIDEO

    return content_type


def get_media_list_from_content(content, regex, is_video=False):
    """
    从内容中获取媒体数据列表
    :param content: 内容
    :param regex: 正则匹配规则
    :param is_video: 是否是视频
    :return:
    """
    if not content:
        return []
    _, _image_list = get_data_from_rich_text(content, regex)
    return get_media_extra_info(
        list(map(lambda item: item.split("-")[0], _image_list)),
        is_video=is_video
    )


def set_qa_video_water_mark_url(source_id, qa_type, content):
    _, video_list = get_data_from_rich_text(content, u'//video[not(@name="new_video")]/@src')
    if video_list:
        get_qiniu_persistent_ids.delay(
            source_id=source_id,
            video_type=qa_type,
            url_list=video_list
        )


class AnswerDB(DataBuilder):
    def getval_answer_has_images(self, obj):
        return True if obj.images.count() else False

    def getval_question_has_images(self, obj):
        return True if obj.question.images.count() else False

    def getval_is_top(self, obj):
        now = datetime.now()
        top = AnswerTop.objects.filter(answer=obj.id, enable=True)
        if top:
            end_time = top[0].end_time
            return now < end_time
        else:
            return False

    def getval_images(self, obj):
        return list(obj.images.filter(
            image_url_source=MEDIA_IMAGE_URL_SOURCE.CREATE
        ).values_list('image_url', flat=True))

    def getval_like_num_not_fake(self, obj):
        return AnswerVote.objects.filter(answer_id=obj.id, is_fake=False).count()

    def getval_like_num_fake(self, obj):
        return AnswerVote.objects.filter(answer_id=obj.id, is_fake=True).count()

    def getval_content(self, obj, need_escape=False):
        return obj.content or ''

    def getval_submit_to_baidu(self, obj):
        return BDAnswer.objects.filter(original_id=obj.id).exists()

    def getval_low_quality(self, obj):
        return obj.low_quality

    def getval_low_quality_deal(self, obj):
        return obj.low_quality_deal

@DB
class AnswerDQ(DataSQLQuery):
    model = Answer
    data_model = AnswerDB

    def filter_user_id(self, srch_key, srch_val, regex=False):
        return Q(user=srch_val)

    def filter_low_quality(self, srch_key, srch_val, regex=False):
        if srch_val == '1':
            return Q(low_quality__gte=1)
        else:
            return Q(low_quality=0)

    def filter_submit_to_baidu(self, srch_key, srch_val, regex=False):
        q = Q(id__in=BDAnswer.objects.all().values_list('original_id', flat=True))
        return q if srch_val == '1' else ~q

    def filter_user_type(self, srch_key, srch_val, regex=False):
        if srch_val == USER_CLASSIFY.NORMAL:
            resp = rpc_client['api/user_classify/ids']().unwrap()
            user_ids = resp.get('user_ids', [])
            return ~Q(user__in=user_ids)

        elif srch_val == USER_CLASSIFY.MODEL:
            resp = rpc_client['api/user_classify/ids']().unwrap()
            user_ids = resp.get('user_ids', [])
            return Q(user__in=user_ids)
        else:
            return Q()

    @classmethod
    def create(cls, **kwargs):
        article_id = kwargs.pop('article_id', None)
        check_type = kwargs.pop('check_type', None)
        kol_id = kwargs.pop('kol_id', None)
        kwargs.pop('answer_id', None)
        vast_id = kwargs.pop('vast_id', None)
        kwargs['user'] = kwargs.pop('user_id', vast_id)
        kwargs['platform'] = kwargs.pop('platform', GRABBING_PLATFORM.HERA)
        images = kwargs.pop('images', [])
        _qa_content_type = qa_content_type_judge(kwargs.get("content", ""))
        kwargs["content_type"] = _qa_content_type

        if kwargs.get('is_recommend'):
            if Answer.objects.filter(question_id=kwargs['question_id'], is_recommend=True).exists():
                raise RPCDFaultException(ERROR.ANSWER_HAS_RECOMMEND, '已有一个推荐回答')
        obj = Answer.objects.create(**kwargs)
        if kwargs.get('is_online') and special_push_limit(user_id=obj.question.user_id, push_type="question_received_answer"):
            author_data = UserService.get_users_by_user_ids([kwargs.get('user')])
            author = author_data.get(int(kwargs.get('user')))
            push_to_question_provider(user_id=obj.question.user_id,
                                      answer_id=obj.id,
                                      question_title=obj.question.title,
                                      user_name=author.nickname)
        if vast_id is not None:
            kol_obj = KolAnswer.objects.get(id=kol_id)
            kol_obj.answer_id = obj.id
            kol_obj.question_id = obj.question.id
            kol_obj.vast_id = vast_id
            kol_obj.save()
        deal_EventDispatcher(obj, user_hierarchy.EventType.ANSWERRECOMMENDED)
        for image in images:
            if image != '':
                AnswerImage.objects.get_or_create(answer_id=obj.id, image_url=image)

        if _qa_content_type == QA_CONTENT_TYPE.VIDEO:
            set_qa_video_water_mark_url(obj.id, VIDEO_SOURCE_TYPE.ANSWER, obj.content)

        # 从内容里取出图片，获取宽高然后入到现有的图片库中
        images_form_content = get_media_list_from_content(kwargs.get('content', ""), u'//img/@src')
        images_list = [item.get("image_url", "") for item in images_form_content]
        gevent_dic = handle_image_type(images_list)
        for image_dic in images_form_content:
            _image_url = image_dic.pop("image_url", "")
            if _image_url:
                AnswerImage.objects.get_or_create(
                    answer_id=obj.id,
                    image_url=_image_url,
                    image_url_source=MEDIA_IMAGE_URL_SOURCE.RICH_TEXT,
                    defaults=image_dic,
                    image_type=gevent_dic.get(_image_url, IMAGE_TYPE.OTHER) or IMAGE_TYPE.OTHER,
                )

        gif_create_webp.delay(qa_id=obj.id, qa_type='answer')
        return to_dict(obj)

    def update(self, updates, **kwargs):
        updates.pop('relation', None)
        add_like_num = updates.pop('add_like_num', None)
        if add_like_num:
            add_like_num = min(add_like_num, 100)
            model = rpc.gaia.person
            model.paging(length=add_like_num)
            model.fields = ['id', 'user_id']
            user = model.filter(is_puppet=1).order_by('?').query()['data']
            user_ids = [x['user_id'] for x in user]
            add_fake_vote_to_answer(user_ids, kwargs['id'])
        images = updates.pop('images', None)
        answer = Answer.objects.get(id=kwargs['id'])
        if updates.get('is_online') and special_push_limit(user_id=answer.question.user_id, push_type="question_received_answer"):
            author_data = UserService.get_users_by_user_ids([answer.user_id])
            author = author_data.get(int(answer.user_id))
            push_to_question_provider(user_id=answer.question.user_id,
                                      answer_id=kwargs['id'],
                                      question_title=answer.question.title,
                                      user_name=author.nickname)
        is_recommend = updates.get('is_recommend')
        if images:
            new_images = set(images)
            old_images = set(answer.images.values_list('image_url', flat=True))
            for image in (new_images - old_images):
                if image != '':
                    AnswerImage.objects.get_or_create(answer_id=answer.id, image_url=image)
            AnswerImage.objects.filter(answer_id=answer.id, image_url__in=(old_images - new_images)).delete()

        if is_recommend:
            notify_recommended_user(answer.user.id, answer.id)
            recommend_answer = list(Answer.objects.filter(question_id=answer.question, is_recommend=True).
                                    values_list('id', flat=True))
            if answer.id in recommend_answer:
                recommend_answer.remove(answer.id)
            if len(recommend_answer):
                raise RPCDFaultException(ERROR.ANSWER_HAS_RECOMMEND, '已有一个推荐回答')
        deal_EventDispatcher(answer, user_hierarchy.EventType.ANSWERRECOMMENDED, is_recommend, 'update')
        if updates.get('online') is False or updates.get('spam_label') is 0:
            query_set = self.model.objects.filter(**kwargs)
            antispam_feedback(query_set, DocType.ANSWER)
        if updates.get('level') == CONTENT_CLASS.FINE or updates.get('level') == CONTENT_CLASS.EXCELLENT:
            answer = Answer.objects.get(**kwargs)
            try:
                doctor = get_doctor_by_user_id(answer.user_id)
            except IndexError:
                doctor = None
            if doctor:
                data_info = doctor.to_dict()
                hospital_type = data_info['hospital']['hospital_type']
                doctor_type = data_info['doctor_type']
                title = data_info['title']
                department = data_info['department']
                hospital_level = data_info['hospital']['hospital_level']
                if all([
                    hospital_type == HOSPITAL_TYPE.PUBLIC,
                    doctor_type == DOCTOR_TYPE.DOCTOR,
                    title != DOCTOR_TITLE_TYPE.EMPTY,
                    department,
                    hospital_level != HOSPITAL_LEVEL.NONE
                ]):
                    try:
                        question = Question.objects.get(id=answer.question_id)
                        new_values = {
                            'user_id':answer.user_id,
                            'name':data_info['name'],
                            'portrait': data_info['portrait'],
                            'doctor_id':  data_info['id'],
                            'doctor_title': title,
                            'doctor_department': data_info['department'],
                            'hospital_type': hospital_type,
                            'hospital_name' : data_info['hospital']['name'],
                            'hospital_level' : hospital_level,
                            'content' : answer.content,
                            'is_recommend': answer.is_recommend,
                            'like_num' : answer.like_num,
                            'is_submit' : True if BDAnswer.objects.filter(question_id=question.id,is_submit=True).exists() else False,
                        }
                        BDAnswer.objects.update_or_create(original_id=kwargs['id'], question=answer.question, defaults=new_values)
                    except RPCDFaultException:
                        raise RPCDFaultException(ERROR.UNIVERSAL, '添加失败')

        if updates.get("content") is not None:
            _qa_content_type = qa_content_type_judge(updates.get('content', ""))
            if _qa_content_type == QA_CONTENT_TYPE.VIDEO:
                set_qa_video_water_mark_url(kwargs["id"], VIDEO_SOURCE_TYPE.ANSWER, updates["content"])

            updates["content_type"] = _qa_content_type

            _images_list = get_media_list_from_content(updates.get("content", ""), u'//img/@src')

            new_images = {image_item["image_url"] for image_item in _images_list if image_item.get("image_url", "")}
            old_images = set(AnswerImage.objects.filter(
                answer_id=answer.id, image_url_source=MEDIA_IMAGE_URL_SOURCE.RICH_TEXT
            ).values_list("image_url", flat=True))

            _update_images = new_images - old_images
            images_list = [item.get("image_url", "") for item in _images_list]
            gevent_dic = handle_image_type(images_list)
            for image_dic in _images_list:
                _image_url = image_dic.get("image_url", "")
                if _image_url and _image_url in _update_images:
                    AnswerImage.objects.get_or_create(
                        answer_id=answer.id,
                        image_url=_image_url,
                        image_url_source=MEDIA_IMAGE_URL_SOURCE.RICH_TEXT,
                        defaults=image_dic,
                        image_type=gevent_dic.get(_image_url, IMAGE_TYPE.OTHER) or IMAGE_TYPE.OTHER,
                    )

            _delete_images = old_images - new_images
            AnswerImage.objects.filter(answer_id=answer.id, image_url__in=_delete_images).delete()
            gif_create_webp.delay(qa_id=answer.id, qa_type='answer')
        return super().update(updates, **kwargs)


class SendAnswerDB(DataBuilder):

    def getval_user_id(self, obj):
        return int(obj.user_id)

    def getval_content(self, obj, need_escape=False):
        return obj.content or ''

@DB
class SendAnswerDQ(DataSQLQuery):
    model = SendAnswer
    data_model = SendAnswerDB

    @classmethod
    def create(cls, **kwargs):

        kwargs["push_time"] = parse_datetime(kwargs["push_time"])
        if kwargs["push_time"] < datetime.now():
            raise RPCDFaultException(ERROR.UNIVERSAL, '请选择当前时间点以后的时间^_^')
        obj = SendAnswer.objects.create(**kwargs)
        eta = kwargs["push_time"] - timedelta(hours=8)
        author_data = UserService.get_users_by_user_ids([kwargs.get('user_id')])
        author = author_data.get(int(kwargs.get('user_id')))
        task = send_answer_on_time.apply_async((obj.id, obj.question.user_id, obj.question.title,
                                                author.nickname, str(kwargs["push_time"])), eta=eta)
        obj.celery_task_id = task.id
        obj.save()
        return to_dict(obj)


class QuestionDB(DataBuilder):
    def getval_content(self, obj, need_escape=False):
        return obj.content or ''

    def getval_question_has_images(self, obj):
        return True if obj.images.count() else False

    def getval_answer_num(self, obj):
        return obj.answers.count()

    def getval_is_top(self, obj):
        now = datetime.now()
        top = AnswerTop.objects.filter(question=obj.id, enable=True)
        if top:
            end_time = top[0].end_time
            return now < end_time
        else:
            return False

    def getval_tags(self, obj):
        tags = QuestionTag.objects.filter(question_id=obj.id)
        return list(tags.values_list('tag', flat=True))

    def getval_images(self, obj):
        return list(obj.images.filter(
            image_url_source=MEDIA_IMAGE_URL_SOURCE.CREATE
        ).values_list('image_url', flat=True))

    def getval_submit_to_baidu(self, obj):
        return obj.bd_answers.filter(is_submit=True).exists()

    def getval_is_real(self, obj):
        return USER_CLASSIFY.MODEL not in obj.user.classify


@DB
class QuestionDQ(DataSQLQuery):
    model = Question
    data_model = QuestionDB

    def filter_user_id(self, srch_key, srch_val, regex=False):
        return Q(user=srch_val)

    def filter_submit_to_baidu(self, srch_key, srch_val, regex=False):
        return Q(id__in=BDAnswer.objects.filter(is_submit=bool(int(srch_val))).values_list('question_id', flat=True))

    def filter_user_type(self, srch_key, srch_val, regex=False):
        if srch_val == USER_CLASSIFY.NORMAL:
            resp = rpc_client['api/user_classify/ids']().unwrap()
            user_ids = resp.get('user_ids', [])
            return ~Q(user__in=user_ids)

        elif srch_val == USER_CLASSIFY.MODEL:
            resp = rpc_client['api/user_classify/ids']().unwrap()
            user_ids = resp.get('user_ids', [])
            return Q(user__in=user_ids)
        else:
            return Q()

    def filter_tags(self, srch_key, srch_val, regex=False):
        question_ids = QuestionTag.objects.filter(tag=int(srch_val)).values_list('question_id', flat=True)
        return Q(id__in=question_ids)

    @classmethod
    def create(cls, **kwargs):
        kol_id = kwargs.pop('kol_id', None)
        kwargs.pop('question_id', None)
        vast_id = kwargs.pop('vast_id', None)
        kwargs['user'] = kwargs.pop('user_id', vast_id)
        kwargs['platform'] = kwargs.pop('platform', GRABBING_PLATFORM.HERA)
        images = kwargs.pop('images', [])
        tags = kwargs.pop('tags', [])

        _qa_content_type = qa_content_type_judge(kwargs.get('content', ""))
        kwargs["content_type"] = _qa_content_type

        obj = Question.objects.create(**kwargs)
        if vast_id is not None:
            #是通过kol入口创建的数据
            kol_obj = KolQuestion.objects.get(id=kol_id)
            kol_obj.question_id = obj.id
            kol_obj.vast_id = obj.user_id
            kol_obj.save()
        for tag in tags:
            QuestionTag.objects.get_or_create(question_id=obj.id, tag=tag)
        for image in images:
            if image != '':
                QuestionImage.objects.get_or_create(question_id=obj.id, image_url=image)

        if _qa_content_type == QA_CONTENT_TYPE.VIDEO:
            set_qa_video_water_mark_url(obj.id, VIDEO_SOURCE_TYPE.QUESTION, obj.content)

        # 从内容里取出图片，获取宽高然后入到现有的图片库中
        images_form_content = get_media_list_from_content(kwargs.get('content', ""), u'//img/@src')
        images_list = [item.get("image_url", "") for item in images_form_content]
        gevent_dic = handle_image_type(images_list)
        for image_dic in images_form_content:
            _image_url = image_dic.pop("image_url", "")
            if _image_url:
                QuestionImage.objects.get_or_create(
                    question_id=obj.id,
                    image_url=_image_url,
                    image_url_source=MEDIA_IMAGE_URL_SOURCE.RICH_TEXT,
                    defaults=image_dic,
                    image_type=gevent_dic.get(_image_url, IMAGE_TYPE.OTHER) or IMAGE_TYPE.OTHER,
                )

        gif_create_webp.delay(qa_id=obj.id, qa_type='question')

        return to_dict(obj)

    def update(self, updates, **kwargs):
        updates.pop('relation', None)
        updates.pop('is_real', None)
        images = updates.pop('images', None)
        tags = updates.pop('tags', None)
        question = Question.objects.get(id=kwargs['id'])
        is_recommend = updates.get('is_recommend')
        if images:
            new_images = set(images)
            old_images = set(question.images.values_list('image_url', flat=True))
            for image in (new_images - old_images):
                if image != '':
                    QuestionImage.objects.get_or_create(question_id=question.id, image_url=image)
            QuestionImage.objects.filter(question_id=question.id, image_url__in=(old_images - new_images)).delete()
        if tags:
            question_tags = QuestionTag.objects.filter(question_id=question.id)
            new_tags = set(map(int, tags))
            old_tags = set(question_tags.values_list('tag', flat=True))
            for tag in (new_tags - old_tags):
                QuestionTag.objects.get_or_create(question_id=question.id, tag=tag)
            QuestionTag.objects.filter(question_id=question.id, tag__in=(old_tags - new_tags)).delete()
        if updates.get('online') is False or updates.get('spam_label') is 0:
            query_set = self.model.objects.filter(**kwargs)
            antispam_feedback(query_set, DocType.QUESTION)

        if not updates.get('is_online'):
            DoctorMessageList.objects.filter(question_id=question.id).update(is_online=False)
        else:
            DoctorMessageList.objects.filter(question_id=question.id).update(is_online=True)

        if updates.get("content") is not None:
            _qa_content_type = qa_content_type_judge(updates.get('content', ""))
            if _qa_content_type == QA_CONTENT_TYPE.VIDEO:
                set_qa_video_water_mark_url(kwargs["id"], VIDEO_SOURCE_TYPE.QUESTION, updates["content"])

            updates["content_type"] = _qa_content_type

            _images_list = get_media_list_from_content(updates.get("content", ""), u'//img/@src')

            new_images = {image_item["image_url"] for image_item in _images_list if image_item.get("image_url", "")}
            old_images = set(QuestionImage.objects.filter(
                question_id=question.id,
                image_url_source=MEDIA_IMAGE_URL_SOURCE.RICH_TEXT
            ).values_list("image_url", flat=True))

            _update_images = new_images - old_images
            images_list = [item.get("image_url", "") for item in _images_list]
            gevent_dic = handle_image_type(images_list)
            for image_dic in _images_list:
                _image_url = image_dic.get("image_url", "")
                if _image_url and _image_url in _update_images:
                    QuestionImage.objects.get_or_create(
                        question_id=question.id,
                        image_url=_image_url,
                        image_url_source=MEDIA_IMAGE_URL_SOURCE.RICH_TEXT,
                        defaults=image_dic,
                        image_type=gevent_dic.get(_image_url, IMAGE_TYPE.OTHER) or IMAGE_TYPE.OTHER,
                    )

            _delete_images = old_images - new_images
            QuestionImage.objects.filter(question_id=question.id, image_url__in=_delete_images).delete()
            gif_create_webp.delay(qa_id=question.id, qa_type="question")

        return super().update(updates, **kwargs)


class AnswerReplyDB(DataBuilder):
    def getval_answer_content(self, obj, need_escape=False):
        return obj.answer.content or ''


@DB
class AnswerReplyDQ(DataSQLQuery):
    model = AnswerReply
    data_model = AnswerReplyDB

    def filter_user_id(self, srch_key, srch_val, regex=False):
        return Q(user=srch_val)

    def filter_user_type(self, srch_key, srch_val, regex=False):
        if srch_val == USER_CLASSIFY.NORMAL:
            resp = rpc_client['api/user_classify/ids']().unwrap()
            user_ids = resp.get('user_ids', [])
            return ~Q(user__in=user_ids)

        elif srch_val == USER_CLASSIFY.MODEL:
            resp = rpc_client['api/user_classify/ids']().unwrap()
            user_ids = resp.get('user_ids', [])
            return Q(user__in=user_ids)
        else:
            return Q()

    @classmethod
    def create(cls, **kwargs):
        kwargs['user'] = kwargs.pop('user_id')
        obj = AnswerReply.objects.create(**kwargs)
        if kwargs.get('is_online', False) and kwargs.get('answer_id', None):
            author_data = UserService.get_users_by_user_ids([kwargs.get('user')])
            author = author_data.get(int(kwargs.get('user')))
            answer_push(answer_id=kwargs.get('answer_id'),
                        comment_id=obj.id,
                        author_name=author.nickname,
                        content=kwargs.get('content'),)
        return to_dict(obj)

    def update(self, updates, **kwargs):
        """
        http://wiki.wanmeizhensuo.com/pages/viewpage.action?pageId=11600136
        按照7715需求，针对创建二级评论时候，会走update方法，但是需要使用create方法，
        """
        if 'reply_content' in updates.keys():
            obj = AnswerReply()
            obj.user = updates['reply_user']
            obj.content = updates['reply_content']
            obj.answer_id = updates['answer_id']
            obj.commented_reply_id = kwargs['id']
            obj.first_reply_id = updates['first_reply_id'] if updates['first_reply_id'].isdigit() else kwargs['id']
            obj.save()
            author_data = UserService.get_users_by_user_ids([updates.get('user_id')])
            author = author_data.get(int(updates.get('user_id')))
            is_commented_reply = True if kwargs['id'] else False
            comment_push(
                answer_id=updates['answer_id'],
                comment_id=kwargs['id'],
                user_id=updates['user_id'],
                content=obj.content,
                author_name=author.nickname,
                is_commented_reply=is_commented_reply
                )
            return to_dict(obj)
        else:
            if updates.get('online') is False or updates.get('spam_label') is 0:
                query_set = self.model.objects.filter(**kwargs)
                antispam_feedback(query_set, DocType.COMMENT)
            return super().update(updates, **kwargs)


class AnswerTopDB(DataBuilder):

    def getval_content(self, obj, need_escape=False):
        if getattr(obj, 'question', None):
            return obj.question.title
        if getattr(obj, 'answer', None):
            return obj.answer.content
        return ''

    def getval_user__last_name(self, obj):
        return obj.user.nickname


@DB
class AnswerTopDQ(DataSQLQuery):
    model = AnswerTop
    data_model = AnswerTopDB

    def create(self, **kwargs):
        order = kwargs.get('order')
        if AnswerTop.objects.filter(order=order).exists():
            raise RPCDFaultException(ERROR.UNIVERSAL, '展示顺序不可重复')
        return super().create(**kwargs)

    def update(self, updates, **kwargs):
        order = updates.get('order')
        if AnswerTop.objects.filter(order=order).exists():
            raise RPCDFaultException(ERROR.UNIVERSAL, '展示顺序不可重复')
        return super().update(updates, **kwargs)


class BDAnswerDB(DataBuilder):

    def getval_question_is_submit(self, obj):
        return BDAnswer.objects.filter(question_id=obj.question_id, is_submit=True).exists()

    def getval_content(self, obj, need_escape=False):
        return obj.content or ''

@DB
class BDAnswerDQ(DataSQLQuery):
    model = BDAnswer
    data_model = BDAnswerDB

    def filter_create_time(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)

    def filter_question_is_submit(self, srch_key, srch_val, regex=False):
        question_id = BDAnswer.objects.filter(is_submit=True).values_list('question_id', flat=True)
        q = Q(question_id__in=question_id)
        return q if srch_val == '1' else ~q

    def update(self, updates, **kwargs):
        bdanswer = BDAnswer.objects.get(**kwargs)
        if not bdanswer.is_submit:
            data = "http://m.igengmei.com/mip/question/{question_id}.html".format(question_id=bdanswer.question_id)
            if settings.DEBUG:
                response = Response()
                response.status_code = 200
                response._content = b'{}'
            else:
                response = requests.post(
                    url='http://data.zz.baidu.com/urls?appid=1598172604619677&token=jCNr7HIVkBdLsC56&type=realtime',
                    headers={'Content-Type': 'text/plain'},
                    data=data.encode('utf8'),
                    timeout=5,
                )
            if response.status_code == 200:
                ret = json.loads(response.text)
                if ret.get('error'):
                    raise RPCDFaultException(ERROR.UNIVERSAL, '提交失败')
                else:
                    bdanswer.is_submit = True
                    bdanswer.save()
        return kwargs


def answer_push(answer_id=None, comment_id=None, author_name=None, content=None):

    if not answer_id:
        return {}
    try:
        answer = Answer.objects.get(id=answer_id)
    except Answer.DoesNotExist:
        return {}

    if answer.user_id:
        comment_push(answer_id=answer_id, comment_id=comment_id, user_id=answer.user_id, author_name=author_name, content=content)