# 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 PROBLEM_REVIEW_STATUS_CHOICES

from talos.models import ReplyCollect
from talos.models.topic import TopicVote, Problem, TopicReply, ProblemTag
from talos.models.diary import DiaryVote, Diary, DiaryTag
from talos.services.tag import TagService
# from talos.libs.vote import VoteTool

from api.models import User, Tag, Order     # TODO CR


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


@receiver(post_save, sender=Problem)
def post_save_problem(sender, instance, created, **kwargs):
    if not created:
        return
    user = User.objects.get(pk=instance.user_id)
    user.person.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 = Tag.objects.get(name=HOT_DISCUSSION_TAG)

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

        elif instance.problem:
            user_id = instance.problem.user_id

        elif instance.diary:
            user_id = instance.diary.user_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

        # 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.id)
                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.id,
                    )
                    dt.save()
            diary.save()


def get_suozhang_selected_tag():
    return Tag.objects.get(name=u'所长精选')


def get_meigou_tag():
    return Tag.objects.get(name=u'美购日记')


@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_selected = get_suozhang_selected_tag()
    suozhang_tag_id = _suozhang_selected.id
    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 = Order.objects.get(pk=instance.diary.order_id)
        cash_back = order.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()
