# -*- coding:utf-8 -*-

import math
import time
import datetime
from operator import itemgetter
from multiprocessing import Pool, Manager
from django.core.management.base import BaseCommand
from django import db

from api.models.doctor import Doctor
from api.models.sign_activity import SignActivity, UserLastSignRecord, UserLastSign, ActivityPrize


def get_activity_info():
    activity = SignActivity.objects.filter(is_online=True, start_time__lte=datetime.datetime.now(),
                                           end_time__gte=datetime.datetime.now()).first()
    if not activity:
        return {}

    return {"activity_id": activity.id}


def transfer_data(result):

    user_ids = result.get('user_ids')
    activity_id = result.get('activity_id')

    user_ids = list(set(user_ids))
    for user_id in user_ids:
        doctor = Doctor.objects.filter(user_id=user_id)
        if doctor:
            continue

        try:
            user_sign = UserLastSignRecord.objects.get(user_id=user_id, available_days__lt=10, is_new=True,
                                          end_time__gte=datetime.datetime(year=2018, month=12, day=27),
                                          end_time__lt=datetime.datetime(year=2018, month=12, day=28))
        except UserLastSignRecord.DoesNotExist:
            continue

        last_record, created = UserLastSign.objects.get_or_create(user_id=user_id, activity_id=activity_id)
        if created:
            last_record.available_days = user_sign.available_days
        else:
            last_record.available_days += user_sign.available_days
        last_record.save()


class Command(BaseCommand):
    def handle(self, *args, **options):
        print('------ starting -----')
        start_time = time.time()
        print("start at: ", start_time)

        queue = Manager().Queue(maxsize=4)
        queue.put(0)  # 触发程序开始

        per_num = 200.0
        all_record = UserLastSignRecord.objects.all().values_list('user_id', flat=True).distinct()
        count = all_record.count()
        cnt = int(math.ceil(count / per_num))

        result = get_activity_info()
        if not result:
            return

        args_list = []
        for _ in range(cnt):
            args_list.append({'user_ids': list(all_record)[_*int(per_num):(_+1)*int(per_num)],
                              "activity_id": result.get('activity_id')})
        db.connections.close_all()
        pool = Pool(processes=4)
        pool.map(transfer_data, args_list)
        pool.close()
        pool.join()
        end_time = time.time()
        print("end at: ", end_time)
        print('total use {} s.'.format(end_time - start_time))
        print('Done!')
