# -*- coding: utf-8 -*-

from django.conf import settings
from django_logit import logit
from django_response import response
from paginator import pagination

from account.models import UserInfo
from message.models import SystemMessageDeleteInfo, SystemMessageInfo, SystemMessageReadInfo, UserMessageInfo
from utils.error.errno_utils import MessageStatusCode, UserStatusCode
from utils.message_utils import system_messages, system_unread_messages
from utils.redis.rmessage import set_system_message_delete_info, set_system_message_read_info


@logit
def message_list_api(request):
    """ 消息列表 """
    user_id = request.POST.get('user_id', '') or request.GET.get('user_id', '')

    messages = UserMessageInfo.MESSAGE_TYPE_INFO

    final_messages = []
    for message in messages:
        msg_type = message['msg_type']
        if msg_type == UserMessageInfo.SYSTEM:
            type_unread_messages = system_unread_messages(user_id, SystemMessageInfo.PAIAI_USER)
        else:
            type_unread_messages = UserMessageInfo.objects.filter(
                to_uid=user_id,
                msg_type=msg_type,
                read=False,
                status=True,
            )
        message['msg_unread_num'] = type_unread_messages.count()
        final_messages.append(message)

    return response(200, 'Get Message List Success', u'获取消息列表成功', {
        'messages': final_messages,
    })


@logit
def message_type_list_api(request, msg_type):
    """ 分类消息列表 """
    user_id = request.POST.get('user_id', '') or request.GET.get('user_id', '')
    page = int(request.POST.get('page') or request.GET.get('page') or 1)
    num = int(request.POST.get('num') or request.GET.get('num') or settings.MESSAGE_NUM_PER_PAGE)

    if msg_type == UserMessageInfo.SYSTEM:
        type_messages = system_messages(user_id, SystemMessageInfo.PAIAI_USER)
    else:
        type_messages = UserMessageInfo.objects.filter(
            to_uid=user_id,
            msg_type=msg_type,
            status=True,
        )
    type_messages = type_messages.order_by(
        '-pk'
    )
    type_messages, left = pagination(type_messages, page, num)
    type_messages = [msg.msg_info(user_id) for msg in type_messages]

    return response(200, 'Get Message List Success', u'获取消息列表成功', {
        'messages': type_messages,
        'left': left,
    })


@logit
def message_type_read_api(request, msg_type=None):
    """ 消息读取 """
    user_id = request.POST.get('user_id', '') or request.GET.get('user_id', '')
    pk = int(request.POST.get('pk', 0) or request.GET.get('pk', 0) or -1)
    _all = (request.POST.get('all', '') or request.GET.get('all', '')).lower()

    # 用户校验
    try:
        user = UserInfo.objects.get(user_id=user_id, status=True)
    except UserInfo.DoesNotExist:
        return response(UserStatusCode.USER_NOT_FOUND)

    # 消息读取
    if msg_type == UserMessageInfo.SYSTEM:
        if pk > 0:  # 系统消息单个读取
            if not SystemMessageInfo.objects.filter(pk=pk, status=True).exists():
                return response(MessageStatusCode.MESSAGE_NOT_FOUND)
            SystemMessageReadInfo.objects.get_or_create(user_id=user_id, msg_id=pk)
        if _all == 'true':  # 系统消息全部读取
            for msg in SystemMessageInfo.objects.filter(src=SystemMessageInfo.PAIAI_USER, status=True):
                SystemMessageReadInfo.objects.get_or_create(user_id=user_id, msg_id=msg.pk)
        set_system_message_read_info(user_id)
    else:
        if pk > 0:  # 用户（点赞／评论）消息单个读取
            UserMessageInfo.objects.filter(pk=pk, to_uid=user_id, status=True).update(read=True)
        if _all == 'true':  # 用户消息（点赞／评论）全部读取
            UserMessageInfo.objects.filter(to_uid=user_id, msg_type=msg_type, status=True).update(read=True)

    return response(200, 'Read Message Success', u'已读消息成功')


@logit
def message_type_delete_api(request, msg_type=None):
    """ 消息删除 """
    user_id = request.POST.get('user_id', '') or request.GET.get('user_id', '')
    pk = int(request.POST.get('pk', 0) or request.GET.get('pk', 0) or -1)
    _all = (request.POST.get('all', '') or request.GET.get('all', '')).lower()

    # 用户校验
    try:
        user = UserInfo.objects.get(user_id=user_id, status=True)
    except UserInfo.DoesNotExist:
        return response(UserStatusCode.USER_NOT_FOUND)

    # 消息删除
    if msg_type == UserMessageInfo.SYSTEM:
        if pk > 0:  # 系统消息单个删除
            if not SystemMessageInfo.objects.filter(pk=pk, status=True).exists():
                return response(MessageStatusCode.MESSAGE_NOT_FOUND)
            SystemMessageDeleteInfo.objects.get_or_create(user_id=user_id, msg_id=pk)
        if _all == 'true':  # 系统消息全部删除
            for msg in SystemMessageInfo.objects.filter(src=SystemMessageInfo.PAIAI_USER, status=True):
                SystemMessageDeleteInfo.objects.get_or_create(user_id=user_id, msg_id=msg.pk)
        set_system_message_delete_info(user_id)
    else:
        if pk > 0:  # 用户（点赞／评论）消息单个删除
            UserMessageInfo.objects.filter(pk=pk, to_uid=user_id, status=True).update(status=False)
        if _all == 'true':  # 用户消息（点赞／评论）全部删除
            UserMessageInfo.objects.filter(to_uid=user_id, msg_type=msg_type, status=True).update(status=False)

    return response(200, 'Delete Message Success', u'消息删除成功')
