# -*- coding: utf-8 -*-
from concurrent.futures import ThreadPoolExecutor
from django.core.management import BaseCommand
from django.utils import timezone

from api.models.sign_v2 import SignUserInfoV2


def handle_points(last_days):
    points_sum = 0
    if last_days < 7:
        for item in range(1, last_days+1):
            points_sum += item * 5
    else:
        for item in range(1, 8):
            points_sum += item * 5

        points_sum += 35 * (last_days - 7)

    return points_sum


def update_value(_id):
    today = timezone.now().day
    yesterday = (timezone.now() + timezone.timedelta(days=-1)).day
    try:
        sign = SignUserInfoV2.objects.get(id=_id)
    except SignUserInfoV2.DoesNotExist:
        return
    last_sign_day = sign.newest_time
    if not last_sign_day:
        return
    last_sign_day = sign.newest_time.day
    sign_days = sign.last_days
    if last_sign_day not in [today, yesterday] or not sign_days:
        return

    sign.points_count = handle_points(sign_days)
    print(sign.id, sign.points_count)
    sign.save()


def update_show_tips(max_id):
    start = 1
    offset = 1000
    while True:
        sign_data = SignUserInfoV2.objects.filter(id__gte=start, id__lte=start+offset)
        if not sign_data and start > max_id:
            break
        sign_data.update(show_tips=True)
        start += offset


class Command(BaseCommand):
    """
    python manage.py sign_points_sync
    """
    def handle(self, *args, **options):
        queryset = SignUserInfoV2.objects.raw(
            "select max(id) id from api_userinfo_sign_v2"
        )
        max_id = int(queryset[0].id) if queryset[0].id else 0
        print('max_id:', max_id)
        if not max_id:
            return

        with ThreadPoolExecutor(5) as tp:
            tp.submit(update_show_tips, max_id)
            for _id in range(1, max_id):
                tp.map(update_value, (_id,))
        print("Done")
