# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, print_function

from cached_property import cached_property
from django.db import models
from django.utils import timezone
from django.utils.html import escape
from gm_serializer import fields
from gm_types.gaia import VOTEOBJECT
from gm_types.mimas import SPAM_LABEL
from gm_upload import ImgUrlField, IMG_TYPE

from rpc.context import get_rpc_remote_invoker
from api.tool.datetime_tool import get_timestamp_or_none


class RPCMixin(object):

    @staticmethod
    def get_rpc_invoker():
        return get_rpc_remote_invoker()

    @classmethod
    def call_rpc(cls, api_endpoint, **kwargs):
        """call rpc.

        get rpc invoker from current ctx, this method only support call rpc sequentially.
        """
        r = cls.get_rpc_invoker()
        result = r[api_endpoint](**kwargs)
        return result.unwrap()


class UserManager(RPCMixin):

    def __call__(self, pk_list):
        """
        :param pk_list:
        :return:
        """
        return self.call_rpc('api/user/get_fundamental_info_by_user_ids', user_ids=pk_list)


class TagManager(RPCMixin):

    def __call__(self, pk_list):
        return self.call_rpc('api/tag/info_by_ids', tag_ids=pk_list)


class Question(models.Model):
    class Meta:
        verbose_name = u'问答'
        db_table = 'api_question'
        app_label = 'answer'

    user = fields.MagicField(type=int, manager=UserManager, ttl=60*5, db_column="user_id")
    title = models.CharField(max_length=128, null=False, verbose_name=u'问题')
    content = models.TextField(null=True, verbose_name=u'描述')
    cover_url = ImgUrlField(img_type=IMG_TYPE.NOWATERMARK, max_length=300, verbose_name=u'原图片地址', null=True, blank=True,
                            default=None)
    is_online = models.BooleanField(verbose_name='是否在线', default=True)
    is_recommend = models.BooleanField(verbose_name='是否推荐', default=False)
    like_num = models.IntegerField(verbose_name='点赞数量', default=0)
    create_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now)
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)
    # is_spam字段已弃用，请使用spam_label
    is_spam = models.BooleanField(verbose_name=u'是否为垃圾回答', default=False)
    spam_label = models.SmallIntegerField(verbose_name=u'spam标签', default=SPAM_LABEL.NORMAL, choices=SPAM_LABEL)

    # from topic
    problem_id = models.IntegerField(verbose_name='帖子id', null=True, default=None, unique=True)
    city_id = models.CharField(max_length=40, null=True, verbose_name=u'用户对应的城市id')

    @cached_property
    def tags(self):
        """
        :return:
        """
        return QuestionTag.objects.filter(question=self)

    @property
    def recommend_answer(self):
        answer = self.answers.filter(is_recommend=True, is_online=True)
        if answer:
            return answer.first()
        return None


class QuestionImage(models.Model):
    class Meta:
        verbose_name = u'问答图片'
        db_table = 'api_question_image'
        app_label = 'answer'

    question = models.ForeignKey(Question, related_name='images')
    image_url = ImgUrlField(img_type=IMG_TYPE.TOPICIMAGE, max_length=300, verbose_name=u'图片地址')
    create_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now)
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)


class QuestionTag(models.Model):
    class Meta:
        db_table = 'api_questiontag'
        app_label = 'answer'

    question = models.ForeignKey(Question)
    tag = fields.MagicField(type=int, manager=TagManager, ttl=60*60*24, db_column="tag_id")


class QuestionVote(models.Model):
    class Meta:
        app_label = 'answer'
        db_table = 'api_question_vote'
        verbose_name = u'问答点赞'

    user = fields.MagicField(type=int, manager=UserManager, ttl=60 * 5, db_column="user_id")
    question = models.ForeignKey(Question, related_name="votes")
    unread = models.BooleanField(default=True)
    is_fake = models.BooleanField(default=False, verbose_name=u"是否机器人点赞")
    create_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now)
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)


class Answer(models.Model):
    class Meta:
        app_label = 'answer'
        db_table = 'api_answer'
        verbose_name = u'问答回复'

    user = fields.MagicField(type=int, manager=UserManager, ttl=60 * 5, db_column="user_id")
    content = models.TextField(verbose_name='回答', null=False)
    cover_url = ImgUrlField(img_type=IMG_TYPE.NOWATERMARK, max_length=300, verbose_name=u'原图片地址', null=True,
                            blank=True, default=None)
    question = models.ForeignKey(Question, verbose_name=u"话题回复", related_name='answers')
    is_online = models.BooleanField(verbose_name='是否在线', default=True)
    is_recommend = models.BooleanField(verbose_name='是否推荐', default=False)
    like_num = models.IntegerField(verbose_name='点赞数量', default=0)
    create_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now)
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)
    # is_spam字段已弃用，请使用spam_label
    is_spam = models.BooleanField(verbose_name=u'是否为垃圾回答', default=False)
    spam_label = models.SmallIntegerField(verbose_name=u'spam标签', default=SPAM_LABEL.NORMAL, choices=SPAM_LABEL)

    # from topicreply
    topicreply_id = models.IntegerField(verbose_name='帖子id', null=True, default=None, unique=True)


class AnswerImage(models.Model):
    class Meta:
        app_label = 'answer'
        db_table = 'api_answer_image'
        verbose_name = u'问答回复图片'

    answer = models.ForeignKey(Answer, related_name='images')
    image_url = ImgUrlField(img_type=IMG_TYPE.TOPICREPLY, max_length=300, verbose_name=u'图片地址')
    create_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now)
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)


class AnswerVote(models.Model):
    class Meta:
        app_label = 'answer'
        db_table = 'api_answer_vote'
        unique_together = ('user', 'answer')

    user = fields.MagicField(type=int, manager=UserManager, ttl=60 * 5, db_column="user_id")
    answer = models.ForeignKey(Answer, verbose_name=u"评论")
    unread = models.BooleanField(default=True)
    is_fake = models.BooleanField(default=False, verbose_name=u"是否机器人点赞")
    create_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now)
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)

    def to_dict(self):
        data = {
            'answer_id': self.answer_id,
            'nickname': self.user.nickname,
            'user_id': self.user_id,
            'vote_time': get_timestamp_or_none(self.create_time),
            'image': '',
            'content': escape(self.answer.content),
            'type': VOTEOBJECT.ANSWER,
            'membership_level': self.user.membership_level,
            'portrait': self.user.portrait,

        }
        return data


class AnswerReply(models.Model):
    class Meta:
        app_label = 'answer'
        db_table = 'api_answer_reply'
        verbose_name = u'问答的评论'

    user = fields.MagicField(type=int, manager=UserManager, ttl=60 * 5, db_column="user_id")
    content = models.TextField(verbose_name='回答', null=False)
    answer = models.ForeignKey(Answer, verbose_name=u"话题回复", related_name='replys')
    first_reply = models.ForeignKey('self', related_name=u'fir_comment', verbose_name=u'一级回复id', null=True,
                                    blank=True, default=None)
    commented_reply = models.ForeignKey('self', related_name=u'comments', verbose_name=u'被评论的回复', null=True,
                                        blank=True, default=None)
    is_online = models.BooleanField(verbose_name='是否在线', default=True)
    like_num = models.IntegerField(verbose_name='点赞数量', default=0)
    create_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now)
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)
    # is_spam字段已弃用，请使用spam_label
    is_spam = models.BooleanField(verbose_name=u'是否为垃圾回答', default=False)
    spam_label = models.SmallIntegerField(verbose_name=u'spam标签', default=SPAM_LABEL.NORMAL, choices=SPAM_LABEL)

    # from topic
    topicreply_id = models.IntegerField(verbose_name='帖子id', null=True, default=None, unique=True)
    is_read = models.BooleanField(verbose_name='是否已读', default=False)


class AnswerVoteReply(models.Model):
    class Meta:
        app_label = 'answer'
        db_table = 'api_answerreply_vote'
        unique_together = ('user', 'answerreply')

    user = fields.MagicField(type=int, manager=UserManager, ttl=60 * 5, db_column="user_id")
    answerreply = models.ForeignKey(AnswerReply, verbose_name=u"评论")
    unread = models.BooleanField(default=True)
    create_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now)
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)


class UserAnswerQuestion(models.Model):
    """
    过渡方案，用于用户的问题与答案混排
    """

    class Meta:
        app_label = 'answer'
        db_table = 'api_user_question_answer'
        verbose_name = u'用户问答混排表'

    user = fields.MagicField(type=int, manager=UserManager, ttl=60 * 5, db_column="user_id")
    answer = models.ForeignKey(Answer, verbose_name=u'用户回答', blank=True, null=True)
    question = models.ForeignKey(Question, verbose_name=u'用户提问', blank=True, null=True)
    create_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now)


class AnswerTop(models.Model):
    class Meta:
        app_label = 'answer'
        db_table = 'api_answer_top'

    question = models.ForeignKey(Question, default=None)
    answer = models.ForeignKey(Answer, default=None)
    order = models.IntegerField('展示顺序', unique=True, default=0)
    top_type = models.IntegerField('置顶类型', default=0)
    start_time = models.DateTimeField('上线时间', default=None)
    end_time = models.DateTimeField('下线时间', default=None)
    enable = models.BooleanField('是否上线', default=True)
    create_time = models.DateTimeField(auto_now_add=True)


class ZoneManager(RPCMixin):

    def __call__(self, pk_list):
        return self.call_rpc('api/zone/list', pks=pk_list)


class OverHeadAnswer(models.Model):
    class Meta:
        app_label = 'answer'
        db_table = "api_overheadanswer"
        verbose_name = u'圈子推荐回答'

    zone = fields.MagicField(type=int, manager=ZoneManager, ttl=60, db_column="zone_id")
    answer = models.ForeignKey(Answer, help_text=u'回答', null=False, default='')
    rank = models.IntegerField(help_text=u'排序顺序', null=False, default=0)
    created_time = models.DateTimeField(help_text=u'创建时间', auto_now_add=True)
    deleted = models.BooleanField(help_text=u'是否已删除', default=False)


class OverHeadQuestion(models.Model):
    class Meta:
        app_label = 'answer'
        db_table = "api_overheadquestion"
        verbose_name = u'圈子推荐问题'

    zone = fields.MagicField(type=int, manager=ZoneManager, ttl=60, db_column="zone_id")
    question = models.ForeignKey(Question, help_text=u'问题', null=False, default='')
    rank = models.IntegerField(help_text=u'排序顺序', null=False, default=0)
    created_time = models.DateTimeField(help_text=u'创建时间', auto_now_add=True)
    deleted = models.BooleanField(help_text=u'是否已删除', default=False)
