# coding=utf-8
from __future__ import unicode_literals, absolute_import


from django.core.management.base import BaseCommand


# CHANNEL_ID = 2
# GIFT_ID = 56

from api.models import ChannelGift
from api.models import ChannelGiftUserRelation
from api.models import User
from api.tool.coupon_tool import create_coupon_info
from django.db import transaction



class Command(BaseCommand):
    def handle(self, *args, **options):
        with open('/tmp/', 'r') as file:
            user_ids = file.read().splitlines()
        channel_gift = ChannelGift.objects.get(business_channel=CHANNEL_ID, gift_id=GIFT_ID)
        for user_id in user_ids:
            user = User.objects.get(pk=user_id)
            print user_id, '... ... ...'
            # try:
            #     ChannelGiftUserRelation.objects.get(user=user, channel_gift=channel_gift)
            #     raise
            # except ChannelGiftUserRelation.DoesNotExist:
            #     pass
            with transaction.atomic():
                relation = ChannelGiftUserRelation.objects.create_without_code(user=user, channel_gift=channel_gift)
                create_coupon_info(channel_gift, user, relation)
