# -*- coding: utf-8 -*-
from mark.services import GrayDevicePool, MarkPush

from django.conf import settings
from django.db.models import F
from celery import shared_task
from mark.models.mark_log import UserMarkLog
from api.tasks.push_task import automate_push_task
from mark.models import MarkPushLog


# 计算命中灰度且版本号大于等于7.26的设备 （每天16点）
@shared_task
def deal_gray_devices():
    GrayDevicePool().deal_devices()


# 计算版本号小于7.26额灰度设备(每天20点)
@shared_task
def deal_low_version_devices():
    GrayDevicePool().deal_low_version_gray_devices()


# 发送首次打卡通知（每天21点）
@shared_task
def mark_push():
    obj = MarkPush()
    obj.mark_push()


# 发送再次打卡通知（每天21点）
@shared_task
def mark_again_push():
    obj = MarkPush()
    obj.mark_push_again()


@shared_task
def do_push_task(user_ids, push_type, alert, extra, first_push=True):
    if first_push:
        # 再次校验用户是否打过卡
        user_ids = set(user_ids)
        marked_user_ids = set(UserMarkLog.objects.using(settings.SLAVE_DB_NAME).filter(
            user_id__in=user_ids,
        ).values_list('user_id', flat=True))
        user_ids = user_ids - marked_user_ids

    automate_push_task(list(user_ids), push_type, alert=alert, extra=extra)


@shared_task
def update_push_log(user_ids):
    user_ids = set(user_ids)
    effect_num = MarkPushLog.objects.filter(
        user_id__in=user_ids,
    ).update(continuous_push_num=F('continuous_push_num') + 1)

    MarkPushLog.objects.filter(
        user_id__in=user_ids,
        continuous_push_num__gte=5,
    ).update(is_effective=False)

    if effect_num != len(user_ids):
        _user_ids = set(MarkPushLog.objects.using(settings.SLAVE_DB_NAME).filter(
            user_id__in=user_ids,
        ).values_list('user_id', flat=True))

        new_user_ids = user_ids - _user_ids

        MarkPushLog.objects.bulk_create(
            [MarkPushLog(
                user_id=user_id,
                continuous_push_num=1,
            ) for user_id in new_user_ids]
        )
