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

from api.models import ServiceItem


class OldService(models.Model):
    class Meta:
        verbose_name = u'福利'
        verbose_name_plural = u'福利'
        db_table = 'api_service'
        app_label = 'api'

    sell_num_limit = models.IntegerField(verbose_name=u'可售数量限制')
    total_num = models.IntegerField(verbose_name=u"总数量")


class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        sss = list(OldService.objects.all().values_list('id', 'sell_num_limit', 'total_num'))
        sd = {s[0]: (s[1], s[2]) for s in sss}

        with transaction.atomic():
            for k, v in sd.iteritems():
                sid = k
                sku_stock = v[0] if v[0] > 0 else 0
                total = v[1] if v[1] > 0 else 0
                sku_stock_lte_zero = sku_stock <= 0
                ServiceItem.objects.filter(service_id=sid).update(total_num=total, sku_stock=sku_stock,
                                                                  sku_stock_lte_zero=sku_stock_lte_zero)
                print "service_id：" + str(sid)

        print "success!"
