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


def real_partner(doctor, end_time):
    now_partner = doctor.business_partener
    change_record = doctor.docbusinessrecord_set.filter(action_time__lte=end_time).last()
    return change_record.to_business if change_record else now_partner


class Command(BaseCommand):
    """
    python manage.py init_20170228_maidansnapshot_business_partner
    """
    def handle(self, *args, **kwargs):
        maidan_snapshots = MaidanOrderSnapshot.objects.all()
        for snapshot in maidan_snapshots:
            try:
                business_partner = real_partner(snapshot.doctor, snapshot.created_time)
                snapshot.business_partner = business_partner
                snapshot.save()
                print snapshot.id
            except Exception as e:
                print snapshot.id, e.message
        print 'DONE'
