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

import codecs
from django.core.management import BaseCommand
from django.db import transaction
from datetime import datetime
from rpc.tool.error_code import gen, CODES
from api.models import Order, ChannelGift, ChannelGiftUserRelation
from api.tool.coupon_tool import create_coupon_info


class Command(BaseCommand):
    """
        双十二订单发美券 在gaia目录下输出send_channal_gift_201612.txt
        python manage.py send_channalgift_201612 gift_id channel_id
    """
    def add_arguments(self, parser):
        parser.add_argument('param', nargs='+', type=str)

    def handle(self, *args, **options):
        gift_id = options['param'][0]
        business_channel_id = options['param'][1]

        result_log = codecs.open('send_channal_gift_201612.txt', 'a', 'utf-8')
        start_time = datetime.strptime(u'2016-12-07 00:00:00', '%Y-%m-%d %H:%M:%S')
        end_created_time = datetime.strptime(u'2016-12-17 23:59:59', '%Y-%m-%d %H:%M:%S')
        end_validate_time = datetime.strptime(u'2016-12-31 23:59:59', '%Y-%m-%d %H:%M:%S')

        orders = Order.objects.filter(created_time__gte=start_time, created_time__lte=end_created_time,
                                      validate_time__gte=start_time, validate_time__lte=end_validate_time)
        for order in orders:
            try:
                user = order.user
                channel_gift = ChannelGift.objects.get(gift_id=gift_id, business_channel_id=business_channel_id)
                has_gift = ChannelGiftUserRelation.objects.filter(user=user, channel_gift=channel_gift).count()
                if channel_gift.limit and channel_gift.limit <= has_gift:
                    raise gen(CODES.COUPON_EXCEED_LIMIT)
                if ChannelGiftUserRelation.objects.filter(channel_gift=channel_gift,
                                                          user_id__isnull=False).count() >= channel_gift.total:
                    raise gen(CODES.COUPON_IS_EMPTY)
                with transaction.atomic():
                    relation = ChannelGiftUserRelation.objects.create_without_code(user=user, channel_gift=channel_gift)
                    create_coupon_info(channel_gift, user, relation)
                print order.id
                result_log.write(order.id + '\n')
            except Exception as e:
                print order.id, e.message
                result_log.write(order.id + e.message + '\n')
                continue
        print 'DONE!'
