# coding: utf-8
# 处理订单美购快照中items字段
import ast
import json

from django.core.management.base import NoArgsCommand
from django.db import transaction
from django_bulk_update.helper import bulk_update

from pay.models import ServiceSnapshot


class Command(NoArgsCommand):
    def handle(self, *args, **options):
        bulk_update_chunk_size = 100
        current_ss_id = 0
        while 1:
            with transaction.atomic():
                service_snapshots = ServiceSnapshot.objects.filter(id__gt=current_ss_id).select_for_update().\
                    order_by('id')[:bulk_update_chunk_size]
                if not service_snapshots:
                    break

                current_ss_id = service_snapshots[::-1][0].id

                for ss_instance in service_snapshots:
                    print u'正在扫描ID：{}'.format(ss_instance.id)
                    if not ss_instance.items:
                        continue
                    try:
                        json.loads(ss_instance.items)
                    except (TypeError, ValueError):
                        items = ast.literal_eval(ss_instance.items)
                        ss_instance.items = json.dumps(items)
                bulk_update(service_snapshots, update_fields=['items'], batch_size=bulk_update_chunk_size)
