# coding=utf8

from __future__ import unicode_literals, absolute_import, print_function

from gm_types.error import ERROR as CODES
from gm_types.gaia import (
    CONST_STRINGS as const_strings,
    TOPIC_TYPE,
)
from gm_types.mimas import NOTICATION_LIST_CATEGORY
from gm_types.push import AUTOMATED_PUSH
from gm_types.user_hierarchy import EventType
from gm_rpcd.all import bind

from talos.tasks import view_increase
from talos.models.topic.topicreply import TopicReply
from talos.services import UserService
from talos.services import get_user_from_context
from utils.rpc import gen, logging_exception, get_current_user
from utils.protocol import gm_protocol
from talos.models.topic import TopicReplyVote, Problem
from user_hierarchy.portal import process_task
from utils.push import vote_push
from talos.tasks.topic import topic_reply_voted_applet_push
from utils.stat_log import SocialStatLogForUserAction
from gm_protocol import GmProtocol
from talos.services.other import get_user_lastest_device_app_version_by_user_id
from utils.common import is_version_gray


@bind('topic/reply/vote')
# @bind_context('talos/topic/reply_vote')
def topic_reply_vote(topic_reply_id):
    user = get_current_user()
    if not user:
        return gen(CODES.LOGIN_REQUIRED)
    try:
        topic_reply = TopicReply.objects.get(pk=topic_reply_id)
    except (TopicReply.DoesNotExist, ValueError):
        return gen(CODES.TOPIC_REPLY_NOT_FOUND)

    if topic_reply.replied_topic_id is not None:
        return gen(CODES.OPERATION_NOT_SUPPORTED)

    t, created = TopicReplyVote.objects.get_or_create(
        user_id=user.id, topic_reply_id=topic_reply.id
    )

    if created:
        topic_reply.like_num += 1
        topic_reply.save()

    else:
        return gen(CODES.TOPIC_REPLY_HAS_VOTED)

    # 给被点赞的评论用户发小程序push
    topic_reply_voted_applet_push.delay(t.id)

    # TODO: seprate diary/topic replyvote
    if created and topic_reply.problem:
        t.save()

        topic_reply_author = UserService.get_user_by_user_id(user_id=topic_reply.user_id)
        topic_reply_author.incr_vote_count()

        # add topicreply vote to topic
        view_increase.delay(const_strings.TOPIC_VOTE, t.topic_reply.problem_id)     # TODO CR 异步任务

    elif created and topic_reply.diary:
        topic_reply.diary.save()

    # add point,growth
    growth_value, point_value, submit_count = 0, 0, 0
    if not user.id == topic_reply.user_id:
        try:
            event_data = process_task(user_id=user.id, event_type=EventType.VOTE_MULTI_TIMES, related_item=t.id)
            growth_value, point_value = event_data['growth_value'], event_data['point_value']
            submit_count = event_data['submit_count']
        except:
            logging_exception()

    # 用户行为埋点，点赞相关
    if topic_reply.problem_id:
        topic = Problem.objects.filter(pk=topic_reply.problem_id).only("id", "diary_id", "topic_type").first()
        _topic_type = topic.topic_type
        if _topic_type in [TOPIC_TYPE.ASK, TOPIC_TYPE.SHARE, TOPIC_TYPE.TOPIC]:  # 日记帖
            _stat_log_data = {
                "user_id": user.id,
                "content_id": topic.diary_id,
                "content_type": SocialStatLogForUserAction.CONTENT_TYPE.diary
            }

        elif _topic_type in [TOPIC_TYPE.USER_ARTICLE, TOPIC_TYPE.COLUMN_ARTICLE]:  # 专栏
            _stat_log_data = {
                "user_id": user.id,
                "content_id": topic.id,
                "content_type": SocialStatLogForUserAction.CONTENT_TYPE.article
            }

        else:
            _stat_log_data = {}

        if _stat_log_data:
            SocialStatLogForUserAction.stat_log_for_like(**_stat_log_data)

    # 增加日记本评论点赞发送push v7715 产品: 连鑫
    push_url = gm_protocol.get_comment_detail(id=topic_reply_id, topic_id=topic_reply.problem_id)
    user_id = topic_reply.user_id
    version = get_user_lastest_device_app_version_by_user_id(user_id)
    # 推送跳转到消息页的赞列表
    if is_version_gray(version, '7.29.0'):
        push_url = GmProtocol().vote_or_favor_list(
            segment_index=NOTICATION_LIST_CATEGORY.VOTE,
            new_vote=True,
        )
    vote_push(user_id=user_id, push_url=push_url, alert=u'又有人给你点赞啦！快来看看是谁被你迷倒了～！', push_type=AUTOMATED_PUSH.TOPIC_REPLY_GET_VOTE)

    return {'growth_value': growth_value, 'point_value': point_value, 'submit_count': submit_count}


@bind('topic/reply/cancel_vote')
def topic_reply_cancel_vote(topic_reply_id):
    user = get_current_user()
    if not user:
        return gen(CODES.LOGIN_REQUIRED)
    try:
        topic_reply = TopicReply.objects.get(pk=topic_reply_id)
    except TopicReply.DoesNotExist:
        return gen(CODES.TOPIC_NOT_FOUND)

    try:
        rel = TopicReplyVote.objects.get(user_id=user.id, topic_reply_id=topic_reply.id)
        rel.delete()

        topic_reply.like_num -= 1
        topic_reply.save()

        topic_reply_author = UserService.get_user_by_user_id(user_id=topic_reply.user_id)
        topic_reply_author.decr_vote_count()

        return gen(CODES.SUCCESS)

    except TopicReplyVote.DoesNotExist:
        return gen(CODES.OPERATION_NOT_SUPPORTED)
