#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2019/1/17

import random
import datetime
from celery import shared_task
from .models import ActivityUserImage
from hera.utils import get_mail_instance
from api.tool.log_tool import logging_exception
from facialactivity.views import send_message


def _send_mail(subject, body, to_list, send=True):
    if not isinstance(to_list, (list, tuple)):
        to_list = [to_list]
    mail = get_mail_instance(subject, body, to_list)
    if send:
        mail.send()

    return mail


def get_defeated_nums(acu):
    """
    count how many people are defeated
    :param click_nums:
    :return:
    """
    if not acu:
        return 0

    real_kick_nums = ActivityUserImage.objects.filter(
        is_online=True,
        is_deleted=False,
        level=acu.level,
        click_nums__lte=acu.click_nums
    ).count()

    return real_kick_nums + acu.fake_exceed_nums


@shared_task
def has_no_click_push_notice():
    # 统计出超过30分钟都没有被点击的图片

    _ids = list(ActivityUserImage.objects.filter(
        is_online=True,
        is_vest=False,
        is_deleted=False,
        is_push=False,
        is_click=False,
        create_time__gte=datetime.datetime.now() - datetime.timedelta(minutes=60)
    ).values_list('id', flat=True))

    for _id in _ids:
        try:
            aui = ActivityUserImage.objects.get(id=_id)
            send_message(aui)
            aui.is_click = True
            aui.is_push = True
            aui.level -= 1
            aui.save()
        except Exception as e:
            logging_exception()
            continue


@shared_task
def add_fake_vest_nums():
    # 定期将马甲用户随机加到真实用户或者马甲用户
    # 给当前用户加上 level以下的随机马甲数, 直到上限
    each_level_vest_nums = {}

    def _count_level_vest(level):
        """
        统计每个等级的马甲用户数
        :param level:
        :return:
        """
        return ActivityUserImage.objects.filter(
            level=level, is_vest=True, is_online=True, is_deleted=False
        ).count()

    def _count_below_level(level, _level=10):
        """
        统计level等级以下马甲数
        :param level:
        :return:
        """
        total = 0
        while level < _level:
            total += _count_level_vest(level)
            level += 1
        return total

    for level in range(1, 10):
        each_level_vest_nums[level] = _count_below_level(level)

    # 所有可用活动用户(包括马甲)
    base = ActivityUserImage.objects.filter(is_online=True, is_deleted=False)
    total = base.count()
    cnt = 0
    step = 500
    while cnt < total:
        cur_ids = list(base.values_list('id', flat=True)[cnt:cnt + step])
        for aid in cur_ids:
            aui = ActivityUserImage.objects.get(id=aid)
            fake_exceed_nums = aui.fake_exceed_nums
            if fake_exceed_nums < each_level_vest_nums.get(aui.level):
                aui.fake_exceed_nums += random.randint(10, 50)
            aui.save()
        cnt += step
