#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
import random

from celery import shared_task
from django.conf import settings
from django.db.models import Q, F

from variety_show.models.young_models import (
    Idol,
    VoteRecord,
)


@shared_task
def idol_add_vote_num(idol_id, vote_num, field_name):
    """
    选手加票
    :param idol_id:
    :param vote_num:
    :param field_name:
    :return:
    """

    _ = Idol.objects.filter(pk=idol_id).update(**{
        field_name: F(field_name) + vote_num,
        "update_time": datetime.datetime.now(),
    })


@shared_task
def vote_record_add_fake_nums(user_id, idol_id, fake_num):
    """
    投票记录表增加虚拟票数
    :param user_id:
    :param idol_id:
    :param fake_num:
    :return:
    """
    obj = VoteRecord.objects.create(
        user_id=user_id,
        idol_id=idol_id,
        votes=fake_num,
        is_fake=True
    )


@shared_task
def fake_vote_num_for_idol(user_id, idol_id):
    """
    虚拟加票
    :param user_id:
    :param idol_id:
    :return:
    """
    _countdown_time = random.choice(range(1, 31))  # 30s

    fake_num = settings.VARIETY_SHOW_YOUNG_CONFIG["virtual_ticket_nums"]
    _random_num = random.choice(range(1, fake_num))
    _fake_num_list = [_random_num, (fake_num - _random_num)]

    for index, num in enumerate(_fake_num_list):

        vote_record_add_fake_nums.apply_async(
            (user_id, idol_id, num),
            countdown=_countdown_time * (index + 1)
        )

    else:
        idol_add_vote_num.apply_async(
            (idol_id, fake_num, "fake_votes"),
            countdown=_countdown_time * len(_fake_num_list)
        )
