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


class Command(BaseCommand):
    def handle(self, *args, **options):
        result_log = open('cashback.txt', 'a')
        error_log = open('error_cashbace.txt', 'a')
        services = Service.objects.all()
        servicereg_items = ServiceRegisterItem.objects.all()
        for service in services.iterator():
            try:
                with transaction.atomic():
                    service.cash_back_rate = 10
                    service.cash_back_fee = int(service.gengmei_price * 0.1)
                    service.save()
                    service_item = []
                    for item in service.items.all():
                        item.cash_back_rate = 10
                        item.cash_back_fee = int(item.gengmei_price * 0.1)
                        item.save()
                        service_item.append(str(item.id))
                    message = u'service_id:{}, serviceitem:{}'.format(
                        service.id, service_item)
                    print message
                    result_log.write(message + '\n')
            except Exception as e:
                print e.message
                message = u'service_id:{}\n'.format(service.id)
                error_log.write(message)
                continue

        for reg_item in servicereg_items.iterator():
            try:
                reg_item.cash_back_rate = 10
                reg_item.cash_back_fee = int(reg_item.gengmei_price * 0.1)
                reg_item.save()
                message = u'reg_item_id:{}'.format(reg_item.id)
                print message
                result_log.write(message + '\n')
            except Exception as e:
                print e.message
                message = u'reg_item_id:{}\n'.format(reg_item.id)
                error_log.write(message)
                continue

        print 'Done!'
