# -*- coding: utf-8 -*-
from datetime import datetime
from api.models import Service
from hippo.models import Merchant
from django.core.management import BaseCommand
from gm_types.gaia import DOCTOR_TYPE


class Command(BaseCommand):
    """
    python django_manage.py service_update_merchant
    美购信息中商户id为Null数据更新
    """

    def handle(self, *args, **options):
        print('start deal service has no merchant at {}'.format(datetime.now()))
        all_service_with_no_merchant = Service.objects.filter(is_online=True, merchant_id=None)
        for service in all_service_with_no_merchant:
            merchant = Merchant.objects.filter(doctor_id=service.doctor_id, is_online=True).first()
            if not merchant:
                if service.doctor.is_merchant or service.doctor.doctor_type == DOCTOR_TYPE.OFFICER:
                    if not service.doctor.merchant:
                        continue
                    merchant_id = service.doctor.merchant.id
                else:
                    officer = service.doctor.hospital.officer
                    if not officer:
                        continue
                    merchant_id = officer.merchant.id
            else:
                merchant_id = merchant.id
            Service.objects.filter(id=service.id).update(merchant_id=merchant_id)
            print('deal service id is {}'.format(service.id))
        print('end deal service has no merchant at {}'.format(datetime.now()))
