# coding=utf-8
import json
from api.models import CouponInfo
from api.models import Coupon
from api.models import CouponSpecialRestrict
from api.models import CouponDoctorRestrict

from django.core.management.base import BaseCommand


class Command(BaseCommand):
    def handle(self, *args, **options):
        for coupon in Coupon.objects.all():
            print coupon.id
            CouponInfo.objects.filter(start_time__isnull=True).filter(end_time__isnull=True).filter(coupon=coupon).update(start_time=coupon.start_time, end_time=coupon.end_time)
            if not coupon.condition:
                continue
            conditions = json.loads(coupon.condition)
            special_ids = conditions.get('specials')
            if not special_ids:
                continue
            for special_id in special_ids:
                CouponSpecialRestrict.objects.get_or_create(
                    special_id=special_id,
                    coupon=coupon
                )

            if coupon.doctor:
                coupon.is_doctor_new = True
                CouponDoctorRestrict.objects.get_or_create(
                    doctor=coupon.doctor,
                    coupon=coupon
                )

            seckill_avail = conditions.get('seckill_avail', False)
            if seckill_avail:
                coupon.seckill_avail = True

            discount_limit = conditions.get('discount_limit', False)
            if discount_limit:
                coupon.discount_limit = True

            prepay_threshold = conditions.get('prepay_threshold')
            if prepay_threshold:
                coupon.prepay_threshold = prepay_threshold

            coupon.announcement = ''
            coupon.save()