# coding: utf-8

"""
各种关于问答的用户召回
"""

from __future__ import absolute_import
from datetime import datetime, timedelta

from celery import shared_task
from django.conf import settings

from gm_types.push import (
    PUSH_INFO_TYPE,
    AUTOMATED_PUSH,
)

from qa.models.answer import (
    InterestForContentUser,
    Question,
    Answer,
)
from qa.libs import _get_content_text
from utils.push import (
    limit_push_count,
    push_task_to_device_ids_multi,
)
from utils.protocol import gm_protocol


def query_answers(answer_ids):
    answer_id2answer_and_question = dict()
    answers = Answer.objects.filter(id__in=answer_ids)
    for answer in answers:
        question = answer.question
        _data = {
            'nickname': answer.user.nickname,
            'question_id': question.id,
            'question_title': question.title,
            'answer_count': question.answer_num,
            'is_online': question.is_online,
            'answer_content': answer.content,
            'comment_count': answer.comment_num,
            'answer_platform': answer.platform,
        }
        answer_id2answer_and_question[answer.id] = _data
    return answer_id2answer_and_question


def update_interest_for_content_user(pk, status):
    """
    status: 0: 未操作，初始值  1：正常完成  2：未找到  3：超过限制
    """
    instance = InterestForContentUser.objects.get(id=pk)
    if instance:
        instance.status=status
        instance.save()


@shared_task
def user_interest_in_content_for_callback(sort_index):
    """
    WIKI: http://wiki.wanmeizhensuo.com/pages/viewpage.action?pageId=33596077
    """
    today = datetime.today()
    start_time = today.replace(hour=0, minute=0, second=0, microsecond=0)
    end_time = start_time + timedelta(days=1)
    push_type = AUTOMATED_PUSH.BASE_USER_INTEREST_FOR_CONTENT
    need_push_info = InterestForContentUser.objects.filter(
        push_type=push_type,
        status=0,
        business_type="answer",
        related_type="question",
        create_time__gt=start_time,
        create_time__lt=end_time,
        sort_index=sort_index,
    )
    answer_ids = [info.business_id for info in need_push_info]
    answer_id2answer_and_question = query_answers(answer_ids)
    for info in need_push_info:
        if not settings.USER_INTEREST_IN_CONTENT_FOR_CALLBACK_GRAY_DEVICE_IDS_ALL_OPEN:
            if info.device_id not in settings.USER_INTEREST_IN_CONTENT_FOR_CALLBACK_GRAY_DEVICE_IDS:
                continue
        answer_and_question = answer_id2answer_and_question.get(info.business_id)
        if not answer_and_question:
            update_interest_for_content_user(info.id, 2)
            continue
        if not limit_push_count(info.device_id, push_type, max_push_count=3):
            update_interest_for_content_user(info.id, 3)
            continue

        push_url = gm_protocol.get_answer_list(info.business_id)
        alert = "@{nickname} 的新回答：{answer_content}".format(
            nickname=answer_and_question["nickname"],
            answer_content=_get_content_text(answer_and_question["answer_content"])
        )
        if len(alert) > 25:
            alert = "{}...".format(alert[:25])
        extra = {
            'type': PUSH_INFO_TYPE.GM_PROTOCOL,
            'pushUrl': push_url,
            'push_url': push_url,
        }
        others = {
            'title': answer_and_question['question_title'],
            'alert': alert
        }
        push_task_to_device_ids_multi(
            [info.device_id],
            extra=extra,
            alert=alert,
            others=others,
            push_type=push_type
        )
        update_interest_for_content_user(info.id, 1)
