# coding=utf-8

from django.core.management import BaseCommand
from django.db import transaction
from django.db.models import Count

from api.models import ChannelGift, ChannelGiftUserRelation, ChannelGiftStatistics


class Command(BaseCommand):
    """
    初始化渠道礼包已领取数量
    python manage.py init_channel_gift_claimed_count
    """

    def handle(self, *args, **options):
        print 'Start init channel gift claimed count'

        bulk_num = 100
        current_gift_id = 0
        while True:
            with transaction.atomic():
                cgids = list(ChannelGift.objects.filter(
                    id__gt=current_gift_id
                ).values_list('id', flat=True).order_by('id')[:bulk_num])

                if not cgids:
                    break

                # NOTE: 可能会导致数据不一致
                channel_gift_to_count = {i.get('channel_gift_id'): i.get('count') for i in
                                         ChannelGiftUserRelation.objects.filter(channel_gift__in=cgids).values(
                                             'channel_gift_id').annotate(count=Count('id'))}

                exist_cgs_cgids = list(ChannelGiftStatistics.objects.filter(
                    channel_gift_id__in=cgids
                ).values_list('channel_gift_id', flat=True))

                print(u'正在处理渠道优惠券ID {} - {}的数据'.format(cgids[0], cgids[-1]))

                ChannelGiftStatistics.objects.bulk_create(
                    [
                        ChannelGiftStatistics(channel_gift_id=channel_gift_id, claimed_count=claimed_count)
                        for channel_gift_id, claimed_count in channel_gift_to_count.items()
                        if channel_gift_id not in exist_cgs_cgids
                    ]
                )
                current_gift_id = cgids[-1]

        print 'Done!'
