# coding=utf-8

import json

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

from pay.models import ServiceSnapshot


class Command(BaseCommand):

    def handle(self, *args, **kwargs):
        progress = 0
        step = 1000
        queryset = ServiceSnapshot.objects.filter(coupon_info__isnull=True)
        snapshots = queryset[:step]
        while snapshots:
            with transaction.atomic():
                for snapshot in snapshots:
                    if json.loads(snapshot.coupon_info or '{}'):
                        continue
                    snapshot.coupon_info = json.dumps({
                        'coupon_id': snapshot.coupon_id,
                        'coupon_value': snapshot.coupon_value,
                        'coupon_name': snapshot.coupon_name,
                        'coupon_info_id': snapshot.coupon_info_id,
                        'coupon_type': snapshot.coupon_type,
                        'coupon_gengmei_percent': snapshot.coupon_gengmei_percent,
                        'coupon_gengmei_value': snapshot.coupon_gengmei_value,
                        'coupon_doctor_value': snapshot.coupon_doctor_value,
                        'doctor_coupon_deduction': 0,
                        'payment_without_coupon': snapshot.payment_without_coupon,
                    })
                    snapshot.save()
            progress += 1
            print('progress: ' + str(progress*step))
            snapshots = queryset[:step]
