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

from api.models import Service


def is_stage(serviceitem):
    count = serviceitem.gengmei_price - serviceitem.pre_payment_price
    if 500 <= count <= 60000:
        return True
    else:
        return False


class Command(BaseCommand):
    """
    批量设置医院的美购为可分期付款
    python manage.py set_service_is_stage_by_hospital
    """

    def handle(self, *args, **options):
        file_log = open('hospital.txt', 'r')
        result_log = open('result_is_stage.txt', 'a')

        for line in file_log:
            try:
                services = Service.objects.filter(doctor__hospital__id=str(line).strip())
                for service in services:
                    if any(map(is_stage, service.items.all())):
                        old_stage = str(service.is_stage)
                        service.is_stage = True
                        service.save()
                        print (service.id)
                        message = str(service.id) + ',' + old_stage + '\n'
                        result_log.writelines(message)
            except Exception as e:
                print e.message
                continue
        print ('Done')
        result_log.close()
        file_log.close()
