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

import datetime
from django.conf import settings
from django.dispatch import receiver
from django.db.models.signals import post_save

from talos.cache.base import vote_cache
from gm_types.gaia import TOPIC_TYPE
from gm_types.gaia import REPLYOBJECT
from gm_types.gaia import PROBLEM_REVIEW_STATUS_CHOICES

from talos.models import ReplyCollect
from talos.models.topic import TopicVote, Problem, TopicReply, ProblemTag, TopicReplyVote
from talos.models.diary import DiaryVote, Diary, DiaryTag
from talos.services.tag import TagService
from talos.cache.reply import reply_cache
from talos.cache.base import reply_cache as reply_msg_cache

from talos.services.order import OrderService
from talos.services.user import UserService
from talos.tools.vote_tool import VoteTool
from talos.tools.replies_tool import ReplyTool

HOT_DISCUSSION_TAG = u'热门讨论'    # TODO CR


@receiver(post_save, sender=TopicVote)
def topicvote_post_save(sender, instance, created, **kwargs):
    if not created:
        return

    user_id = instance.topic.user_id
    vt = VoteTool(vote_cache, user_id)
    vt.receive_topic_vote(instance.id)

    vt_v1 = VoteTool(vote_cache, user_id, new_version=True)
    vt_v1.receive_topic_vote(instance.id)


@receiver(post_save, sender=DiaryVote)
def diaryvote_post_save(sender, instance, created, **kwargs):
    if not created:
        return

    user_id = instance.diary.user_id
    dt = VoteTool(vote_cache, user_id)
    dt.receive_diary_vote(instance.id)

    dt_v1 = VoteTool(vote_cache, user_id, new_version=True)
    dt_v1.receive_diary_vote(instance.id)


@receiver(post_save, sender=TopicReplyVote)
def topicreplyvote_post_save(sender, instance, created, **kwargs):
    if not created:
        return

    user_id = instance.topic_reply.user_id
    dt = VoteTool(vote_cache, user_id)
    dt.receive_topic_reply_vote(instance.id)

    dt_v1 = VoteTool(vote_cache, user_id, new_version=True)
    dt_v1.receive_topic_reply_vote(instance.id)


@receiver(post_save, sender=Problem)
def post_save_problem(sender, instance, created, **kwargs):
    if not created:
        return
    user = UserService.get_user_by_user_id(user_id=instance.user_id)
    user.incr_topic_count()     # TODO CR 把相关incr_vote decr_vote decr_topic_count挪到signal


@receiver(post_save, sender=TopicReply)
def reply_post_save(sender, instance, created, **kwargs):
    if created:
        hot_discussion_tag = TagService.get_tag_by_name(name=HOT_DISCUSSION_TAG)

        # 处理回复数据，加到redis中
        user_id = None
        reply_type = None
        if instance.replied_topic:
            reply_type = REPLYOBJECT.TOPIC
            user_id = instance.replied_topic.user_id

        elif instance.problem:
            reply_type = REPLYOBJECT.PROBLEM
            user_id = instance.problem.user_id

        elif instance.diary:
            user_id = instance.diary.user_id

        reply_cache.cache_received_comment_ids(user_id, instance.id)

        ReplyCollect.objects.create(created_time=instance.reply_date, user_id=instance.user_id,
                                    topic_reply_id=instance.id, answer_id=None,
                                    reply_user_id=user_id)
        # if instance is diary and return
        if instance.diary:
            return

        if user_id != instance.user_id:
            rt = ReplyTool(reply_msg_cache, user_id)
            if reply_type == REPLYOBJECT.TOPIC:
                rt.receive_topic_reply(instance.id)
            elif reply_type == REPLYOBJECT.PROBLEM:
                rt.receive_problem_reply(instance.id)

        # tag hot topics
        topic_type = instance.problem.topic_type
        if topic_type == TOPIC_TYPE.SHARE:
            threshold = settings.HOT_DISCUSSION_TAG_DIARY_SHRESHOLD

        elif topic_type == TOPIC_TYPE.ASK:
            threshold = settings.HOT_DISCUSSION_TAG_CONSULT_SHRESHOLD

        elif topic_type == TOPIC_TYPE.TOPIC:
            threshold = settings.HOT_DISCUSSION_TAG_DISCUSS_SHRESHOLD

        else:
            return

        if instance.problem.reply_num >= threshold:
            problem_id = instance.problem_id
            tag_ids = ProblemTag.objects.filter(problem_id=problem_id).values_list('tag_id', flat=True)
            tags = TagService.get_tags_by_tag_ids(tag_ids)
            tagged = filter(lambda t: t.name == HOT_DISCUSSION_TAG, tags)
            if not tagged:
                pt = ProblemTag(problem_id=instance.problem_id,
                                tag_id=hot_discussion_tag.get('tag_queried').get('id_list')[0])
                pt.save()

        diary = instance.problem.diary
        if not diary:
            return

        if instance.problem and instance.problem.diary:
            diary.reply_num = diary.reply_num + 1
            if diary.reply_num >= settings.HOT_DISCUSSION_TAG_DIARY_SHRESHOLD:
                tag_ids = DiaryTag.objects.filter(diary_id=diary.id).values_list('tag_id', flat=True)
                tags = TagService.get_tags_by_tag_ids(tag_ids)
                tagged = filter(lambda t: t.name == HOT_DISCUSSION_TAG, tags)
                if not tagged:
                    dt = DiaryTag(
                        diary_id=diary.id,
                        tag_id=hot_discussion_tag.get('tag_queried').get('id_list')[0],
                    )
                    dt.save()
            diary.save()


def get_suozhang_selected_tag():
    result = TagService.get_tag_by_name(name=u'所长精选')
    return result.get('tag_queried').get('id_list')[0] if result else ''


def get_meigou_tag():
    result = TagService.get_tag_by_name(name=u'美购日记')
    return result.get('tag_queried').get('id_list')[0] if result else ''


@receiver(post_save, sender=Diary)
def diary_add_suozhang_selected_tag(sender, instance, created, **kwargs):
    if instance.is_headline and instance.headline_time is None:
        # 设置了首页推荐并且首页推荐时间为None
        instance.headline_time = datetime.datetime.now()
        instance.save()
    elif not instance.is_headline and instance.headline_time is not None:
        # 取消了首页推荐并且存在首页推荐时间
        instance.headline_time = None
        instance.save()

    suozhang_tag_id = get_suozhang_selected_tag()
    diary_id = instance.id
    tag_ids = list(DiaryTag.objects.filter(diary_id=diary_id).values_list('tag_id', flat=True))
    if suozhang_tag_id in tag_ids:
        has_tagged = True
    else:
        has_tagged = False
    if instance.is_essence and not has_tagged:
        dt = DiaryTag(
            diary_id=diary_id,
            tag_id=suozhang_tag_id,
        )
        dt.save()
        return

    if not instance.is_essence and has_tagged:
        dt = DiaryTag.objects.get(diary_id=diary_id, tag_id=suozhang_tag_id)
        dt.delete()


@receiver(post_save, sender=Problem)
def topic_cash_back_count(sender, created, instance, **kwargs):
    try:
        order = OrderService.get_order_from_order_id(id=instance.diary.order_id)
        cash_back = order.get('cashback')
    except:
        return

    num = instance.diary.topics.filter(is_online=True,
                                       review_status=PROBLEM_REVIEW_STATUS_CHOICES.OK).count()
    if cash_back.topic_cash_back_num != num:
        cash_back.topic_cash_back_num = num
        cash_back.save()
