from __future__ import unicode_literals, absolute_import, print_function

import random
import datetime
from gm_protocol import GmProtocol
from gm_types.push import PUSH_INFO_TYPE, AUTOMATED_PUSH
from gm_types.error import ERROR
from gm_types.gaia import (
    CONST_STRINGS,
    LIST_TRACTATE_FROM,
)
from gm_types.mimas import NOTICATION_LIST_CATEGORY

from qa.utils.statistic import get_async_args_v2
from gm_rpcd.all import bind
from talos.services import UserService
from talos.tasks import tractate_fake_vote, fake_view_num

from talos.cache.base import vote_cache, tractate_pv_cache, tractate_vote_count_cache, tractate_reply_vote_count_cache
from utils.push import vote_push
from utils.tasks import vote_applet_push
from talos.services.user import UserService
from talos.services.tractate import TractateVoteService, TractateReplyService
from talos.services.tractate import TractateReplyVoteService
from talos.services.tractate import TractateService
from talos.tools.vote_tool import VoteTool
from utils.rpc import gen, get_current_user
from utils.stat_log import SocialStatLogForUserAction
from communal.tasks import intelligent_push_task
from talos.services.other import get_user_lastest_device_app_version_by_user_id
from utils.common import is_version_gray


@bind('mimas/tractate/vote')
def create(tractate_id):
    """
    新帖子点赞
    :return:
    """
    user = get_current_user()
    if not user:
        return gen(ERROR.LOGIN_REQUIRED)

    tractate = TractateService.healthy(tractate_id)
    tv, created = TractateVoteService.create(tractate=tractate, user_id=user.id)
    if not created:
        return {
            "vote_amount": tractate.vote_amount
        }

    # 对作者添加点赞数
    author = UserService.get_user_by_user_id(tractate.user_id)
    author.incr_vote_count()

    vote_num = TractateService.inc_tractate_vote(tractate)

    vote_tool = VoteTool(redis_c=vote_cache, user_id=tractate.user_id, new_version=True)
    vote_tool.receive_tractate_vote(tv.id)

    # 点赞推送
    alert = u'有1位朋友给你点了赞，快来看看吧>>'
    push_url = GmProtocol().get_tractate_detail(
        tractate_id=tractate_id,
        tractate_detail_from=LIST_TRACTATE_FROM.NOTICE_VOTE
    )
    version = get_user_lastest_device_app_version_by_user_id(tractate.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,
        )
    intelligent_push_task.delay(
        content_id=tractate.id,
        user_ids=[tractate.user_id],
        push_type=AUTOMATED_PUSH.TRACTATE_GET_VOTED,
        platform=None,
        extra={
            'type': PUSH_INFO_TYPE.GM_PROTOCOL,
            'pushUrl': push_url,
            'push_url': push_url,
        },
        alert=alert,
        others={
            "title": "@{} 给你点了赞".format(user.nick_name),
            "alert": alert,
        },
        labels={},
    )
    # 虚拟增加pv
    view_num = fake_view_num(*[5, 15])
    tractate_pv_cache.incrby(str(tractate.id), view_num)  # 浏览量cache

    # 用户行为标签，点赞相关
    SocialStatLogForUserAction.stat_log_for_like(
        content_type=SocialStatLogForUserAction.CONTENT_TYPE.user_post,
        user_id=user.id,
        content_id=tractate_id
    )

    return {
        "vote_amount": vote_num
    }


@bind('mimas/tractate/vote_cancel')
def cancel(tractate_id):
    """
    新帖子取消点赞
    :return:
    """
    user = get_current_user()
    if not user:
        return gen(ERROR.LOGIN_REQUIRED)

    tractate = TractateService.healthy(tractate_id)
    tv, cancel_status = TractateVoteService.cancel(tractate, user.id)
    if not cancel_status:
        return {
            "vote_amount": tractate.vote_amount
        }

    author = UserService.get_user_by_user_id(tractate.user_id)
    author.decr_vote_count()

    vote_num = TractateService.dec_tractate_vote(tractate)

    vote_tool = VoteTool(redis_c=vote_cache, user_id=tractate.user_id, new_version=True)
    vote_tool.remove_tractate_vote(tv.id)

    return {
        "vote_amount": vote_num
    }


@bind('mimas/tractate/reply_vote')
def reply_vote_create(reply_id):
    """
    新帖子回复点赞
    :return:
    """
    user = get_current_user()
    if not user:
        return gen(ERROR.LOGIN_REQUIRED)

    reply = TractateReplyService.healthy(reply_id)
    reply, reply_vote = TractateReplyVoteService.create(user_id=user.id, reply=reply)

    vote_num = TractateReplyService.inc_reply_vote(reply)

    vote_tool = VoteTool(redis_c=vote_cache, user_id=reply.user_id, new_version=True)
    vote_tool.receive_tractate_reply_vote(reply_vote.id)
    # 消息推送
    push_url = GmProtocol().get_tractate_detail(comment_id=reply_id, tractate_id=reply_vote.tractate_id,
                                                tractate_detail_from=LIST_TRACTATE_FROM.NOTICE_VOTE)
    version = get_user_lastest_device_app_version_by_user_id(reply.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=reply.user_id,
        push_url=push_url,
        alert=u'{user_name}赞了你的回复{content}'.format(
            user_name=str(user.nick_name), content=reply.content[:10]
        ),
        push_type=AUTOMATED_PUSH.TRACTATE_REPLY_GET_VOTED
    )

    # 小程序订阅消息推送
    vote_applet_push.delay(reply_vote.id)

    # 用户行为标签，点赞相关
    SocialStatLogForUserAction.stat_log_for_like(
        content_type=SocialStatLogForUserAction.CONTENT_TYPE.user_post,
        user_id=user.id,
        content_id=reply.tractate_id
    )

    return {
        "vote_amount": vote_num
    }


@bind('mimas/tractate/reply_vote/cancel')
def reply_vote_cancel(reply_id):
    """
    新帖子回复取消点赞
    :param reply_id:
    :return:
    """
    user = get_current_user()
    if not user:
        return gen(ERROR.LOGIN_REQUIRED)

    reply = TractateReplyService.healthy(reply_id)
    TractateReplyVoteService.cancel(user.id, reply)
    vote_num = TractateReplyService.dec_reply_vote(reply)

    return {
        "vote_amount": vote_num
    }


@bind('mimas/tractate/read_votes')
def tractate_read_all():
    """
    更新未读消息状态
    :return:
    """
    user = get_current_user()
    if not user:
        return gen(ERROR.LOGIN_REQUIRED)

    TractateVoteService.set_read_by_user_id(user.id)


@bind('mimas/tractate/read_reply_votes')
def tractate_reply_read_all():
    """
    更新未读消息状态
    :return:
    """
    user = get_current_user()
    if not user:
        return gen(ERROR.LOGIN_REQUIRED)

    TractateReplyVoteService.set_read_by_user_id(user.id)


@bind('mimas/tractate/unread_count')
def tractate_unread_num(tractate_id):
    """
    点赞未读数
    :return:
    """
    count = TractateVoteService.unread_count(tractate_id)

    return {'count': count}
