# coding=utf-8
from django.core.management import BaseCommand
from django.db import transaction

from api.models import Order, ServiceItem

class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        sss = list(Order.objects.filter(service_item_id__isnull=True)
                   .exclude(service_item_key='').values_list('id',
                                                             'service_id',
                                                             'service_item_key', ))

        sk2sii = {}

        for i in sss:
            oid = i[0]
            sid = i[1]
            key = i[2]

            service_item_id = None

            if not sk2sii.has_key((sid, key)):
                d = ServiceItem.objects.filter(service_id=sid,key=key)
                if len(d) == 1:
                    service_item_id = d[0].id
            else:
                service_item_id = sk2sii[(sid, key)]

            if service_item_id:
                with transaction.atomic():
                    Order.objects.filter(id=oid).update(service_item_id=service_item_id)
            else:
                print "no id for order: " + str(oid)

            sk2sii[(sid, key)] = service_item_id

        print "success!"