import datetime

from gm_rpcd.all import bind
from gm_types.error import ERROR
from gm_types.mimas import ATTENTION_NOTIFY_TYPE

from talos.models.follow_msg_notify import FollowMsgNotification
from utils.rpc import get_current_user, gen


@bind('mimas/attention_msg/notify')
def attention_messages_received():
    """
    关注 消息通知  未读消息数
    :param fans_id:
    :return:
    """
    result = {
        'total_unread': 0,
        'question_unread': 0,
        'diary_unread': 0,
        'tractate_unread': 0,
        'live_unread': 0,
    }
    user = get_current_user()
    if not user:
        return result

    matched_ids = list(FollowMsgNotification.objects.filter(
        fans_id=user.id, is_online=True, is_read=False,
    ).values_list('id', flat=True))

    # 获取不同类型的未读数
    question_unread = FollowMsgNotification.objects.filter(
        id__in=matched_ids, source_type=ATTENTION_NOTIFY_TYPE.QUESTION
    ).count()
    diary_unread = FollowMsgNotification.objects.filter(
        id__in=matched_ids, source_type=ATTENTION_NOTIFY_TYPE.DIARY
    ).count()
    tractate_unread = FollowMsgNotification.objects.filter(
        id__in=matched_ids, source_type=ATTENTION_NOTIFY_TYPE.TRACTATE
    ).count()
    live_unread = FollowMsgNotification.objects.filter(
        id__in=matched_ids, source_type=ATTENTION_NOTIFY_TYPE.LIVE
    ).count()

    result = {
        'total_unread': len(matched_ids),
        'question_unread': question_unread,
        'diary_unread': diary_unread,
        'tractate_unread': tractate_unread,
        'live_unread': live_unread,
    }

    return result


@bind('mimas/attention_msg/read')
def attention_messages_read(source_type=None):
    """
    关注 消息通知 已读状态修改
    :param source_type:
    :return:
    """
    user = get_current_user()
    if not user:
        return gen(ERROR.LOGIN_REQUIRED)

    if source_type not in ATTENTION_NOTIFY_TYPE:
        return

    if source_type == ATTENTION_NOTIFY_TYPE.UNDEFINED:   # read all
        FollowMsgNotification.objects.filter(
            fans_id=user.id, is_read=False,
        ).update(is_read=True, update_time=datetime.datetime.now())

    else:
        FollowMsgNotification.objects.filter(
            fans_id=user.id, is_read=False, source_type=source_type,
        ).update(is_read=True, update_time=datetime.datetime.now())
