# -*- coding: utf-8 -*-
# @Time    : 2019/9/9 9:59 AM
# @Author  : Esse
# @FileName: format_20190909_conversation_unread_num.py


from django.core.management import BaseCommand
from services.unread.stat import UserUnread
from api.models import Conversation,ConversationUserStatus
from api.models.user import User
import message.signals as message_signals


class Command(BaseCommand):
    """
    私信mysql es redis未读数一致性同步
    python manage.py format_20190909_conversation_unread_num
    """

    def handle(self, *args, **options):
        # 拿到所有mysql中已读的cus
        cus = ConversationUserStatus.objects.filter(read_status=False)
        for cu in cus:
            # 判断这些已读的cus在redis中是否还有未读数留存
            if UserUnread(cu.user_id).get_conversation_unread(cu.conversation_id) > 0:
                view_user = User.objects.get(id=cu.user_id)
                from services.notify import notify
                uids_1, uids_2 = cu.conversation.user_ids()
                # 清除redis未读数
                notify("conversation/clear", user_id=view_user.id, data={
                    'conversation_id': cu.conversation_id,
                    'send_uid': view_user.id,
                    'send_nickname': view_user.last_name,
                    'target_uid': uids_2 if uids_1 == view_user.id else uids_1,
                })
                # 通知es更改已读状态
                message_signals.post_touch_conversation(view_user, cu.conversation)
                print('{}:{}'.format(cu.user_id, cu.conversation_id))
