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

from django.conf import settings
from django.http import JsonResponse

from account.models import UserInfo
from message.models import SystemMessageDeleteInfo, SystemMessageInfo, SystemMessageReadInfo, UserMessageInfo
from utils.error.errno_utils import MessageStatusCode, UserStatusCode
from utils.error.response_utils import response
from utils.page_utils import pagination
from utils.redis.rmessage import (get_system_message_delete_info, get_system_message_read_info,
                                  set_system_message_delete_info, set_system_message_read_info)


def message_list_api(request):
    """
    消息列表
    :param request:
    :return:
    """
    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:
            read_message_ids = get_system_message_read_info(user_id)
            deleted_message_ids = get_system_message_delete_info(user_id)
            type_unread_messages = SystemMessageInfo.objects.filter(
                status=True,
            ).exclude(
                pk__in=list(set(read_message_ids + deleted_message_ids)),
            )
        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 JsonResponse({
        'status': 200,
        'message': u'获取消息列表成功',
        'data': {
            'messages': final_messages,
        },
    })


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

    if msg_type == UserMessageInfo.SYSTEM:
        deleted_message_ids = get_system_message_delete_info(user_id)
        type_messages = SystemMessageInfo.objects.filter(
            status=True,
        ).exclude(
            pk__in=deleted_message_ids,
        )
    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 JsonResponse({
        'status': 200,
        'message': u'获取消息列表成功',
        'data': {
            'messages': type_messages,
            'left': left,
        },
    })


def message_type_read_api(request, msg_type=None):
    """
    消息读取
    :param request:
    :return:
    """
    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)
    except UserInfo.DoesNotExist:
        return response(UserStatusCode.USER_NOT_FOUND)

    # 消息读取
    if msg_type == UserMessageInfo.SYSTEM:
        if pk > 0:  # 系统消息单个读取
            if not SystemMessageInfo.objects.filter(pk=pk).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(status=True):
                SystemMessageReadInfo.objects.get_or_create(user_id=user_id, msg_id=msg.pk)
        get_system_message_read_info(user_id)
    else:
        if pk > 0:  # 用户（点赞／评论）消息单个读取
            UserMessageInfo.objects.filter(pk=pk, to_uid=user_id).update(read=True)
        if _all == 'true':  # 用户消息（点赞／评论）全部读取
            UserMessageInfo.objects.filter(to_uid=user_id, msg_type=msg_type).update(read=True)

    return JsonResponse({
        'status': 200,
        'message': u'已读消息成功',
    })


def message_type_delete_api(request, msg_type=None):
    """
    消息删除
    :param request:
    :param msg_type:
    :return:
    """
    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)
    except UserInfo.DoesNotExist:
        return response(UserStatusCode.USER_NOT_FOUND)

    # 消息删除
    if msg_type == UserMessageInfo.SYSTEM:
        if pk > 0:  # 系统消息单个删除
            if not SystemMessageInfo.objects.filter(pk=pk).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(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).update(status=False)
        if _all == 'true':  # 用户消息（点赞／评论）全部删除
            UserMessageInfo.objects.filter(to_uid=user_id, msg_type=msg_type).update(status=False)

    return JsonResponse({
        'status': 200,
        'message': u'消息删除成功',
    })
