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

from api.models import Doctor


class Command(BaseCommand):
    """
    关闭买单
    1.所有上线状态为否的医生；
    2.所有在线美购数为0的医生；
    """

    def handle(self, *args, **options):
        doctors = Doctor.objects.exclude(maidansettingapply__status=MAIDAN_REVIEW_STATUS.UNDER_REVIEW)
        result_log = open('success_maidandoctor.txt', 'a')
        for doctor in doctors.iterator():
            try:
                with transaction.atomic():
                    if not doctor.is_online or not doctor.services.filter(is_online=True).exists():
                        doctor.maidansetting.is_open = False
                        doctor.maidansetting.save()
                        if getattr(doctor, 'maidansettingapply', None):
                            doctor.maidansettingapply.is_open = False
                            doctor.maidansettingapply.save()
                        print doctor.id
                        result_log.writelines(str(doctor.id) + '\n')
            except Exception as e:
                continue
        print u'Done'
