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

from api.models import Service
from api.models import ServiceItem, ServiceRegisterItem


class Command(BaseCommand):
    """
    python manage.py set_service_discount
    """

    def handle(self, *args, **options):
        file_log = open('service.txt', 'r')
        result_log = open('result_service.txt', 'a')
        for line in file_log:
            try:
                with transaction.atomic():
                    service_id = int(line.strip())
                    print service_id
                    service = Service.objects.get(id=service_id)
                    old_discount = service.discount
                    service.discount = int(math.ceil(service.gengmei_price * 0.1))
                    service.save()
                    serviceitems = ServiceItem.objects.filter(service_id=service_id, is_delete=False)
                    for serviceitem in serviceitems:
                        old_serviceitemdiscount = serviceitem.discount
                        serviceitem.discount = int(math.ceil(serviceitem.gengmei_price * 0.1))
                        serviceitem.save()
                        serviceregisteritem = ServiceRegisterItem.objects.get(serviceitem_id=serviceitem.id,
                                                                              is_delete=False)
                        old_serviceregisteritemdiscount = serviceregisteritem.discount
                        serviceregisteritem.discount = int(math.ceil(serviceregisteritem.gengmei_price * 0.1))
                        serviceregisteritem.save()
                        message = u'serviceid:{0},{1},{2}; serviceitemID:{3},{4},{5}; serviceregisterItemId:{6},{7},' \
                                  u'{8} \n'.format(service_id, old_discount, service.discount, serviceitem.id,
                                                   old_serviceitemdiscount,
                                                   serviceitem.discount, serviceregisteritem.id,
                                                   old_serviceregisteritemdiscount,
                                                   serviceregisteritem.discount)
                        result_log.writelines(message)
            except Exception as e:

                print e.message
                continue
        print (u'更新成功!')
        result_log.close()
        file_log.close()
