# coding=utf-8
import datetime
from django.core.management import BaseCommand
from gm_types.gaia import ACTIVITY_TYPE_ENUM

from api.models import Special, SKUPriceRule


class Command(BaseCommand):
    """
    python manage.py update_20170103_set_price_rule_on_special
    批量设置专场和秒杀的默认价格规则
    create by oldman 2017-01-03
    """

    def handle(self, *args, **options):
        specials = Special.objects.filter()
        for special in specials:
            try:
                skupricerules = SKUPriceRule.objects.filter(
                    activity_type=ACTIVITY_TYPE_ENUM.SECKILL if special.is_seckill else ACTIVITY_TYPE_ENUM.SPECIAL,
                    activity_id=special.id)
                if skupricerules.exists():
                    skupricerule = skupricerules[0]
                    skupricerule.is_enable = True
                    skupricerule.refund_anytime = True
                    skupricerule.can_use_points = True
                    skupricerule.share_get_cashback = True
                    skupricerule.save()
                else:
                    skupricerule = SKUPriceRule.objects.create(
                        name=special.title,
                        is_enable=True,  # todo 确认默认值
                        start_time=special.start_time,
                        end_time=special.end_time if special.end_time else datetime.datetime.now(),
                        activity_type=ACTIVITY_TYPE_ENUM.SECKILL if special.is_seckill else ACTIVITY_TYPE_ENUM.SPECIAL,
                        activity_id=special.id,
                        refund_anytime=True,
                        can_use_points=True,
                        share_get_cashback=True,
                    )
            except Exception as e:
                print u'error', e.message, special.id
                continue

        print "done!"