from celery import shared_task
from django.conf import settings
from gm_types.mimas.enum import ATTENTION_NOTIFY_TYPE

from social.models import _FollowInfoCacheStore, UserFollow
from talos.models.follow_msg_notify import FollowMsgNotification


follow_cache = _FollowInfoCacheStore(uid=None)


@shared_task
def create_information_db(user_id, source_type, business_id):
    """
    关注用户的动态变更 入库（发布帖子、直播、日记本、问题）
    :param user_id:
    :param source_type: 帖子、直播、日记本、问题
    :param business_id: 帖子、直播、日记本、问题id
    :return:
    """
    if source_type not in ATTENTION_NOTIFY_TYPE:
        return

    fans_ids = follow_cache.get_all_fans(follow_id=user_id)
    if not fans_ids and settings.DEBUG:   # 测试环境gaia关注缓存和mimas关注缓存不一样 所以需要读库  但是线上一致
        fans_ids = list(UserFollow.objects.filter(
            follow_id=user_id, bond=True
        ).values_list('user_id', flat=True))
    if not fans_ids:
        return

    msg_obj_list = []
    for fans_id in fans_ids:
        msg_obj = FollowMsgNotification(
            user_id=user_id,
            fans_id=fans_id,
            source_type=source_type,
            business_id=business_id,
            is_read=False,
            is_online=True,
        )
        msg_obj_list.append(msg_obj)

    while msg_obj_list:

        FollowMsgNotification.objects.bulk_create(msg_obj_list[:100])
        msg_obj_list = msg_obj_list[100:]
