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

from api.models import Order


class Command(BaseCommand):
    """
    python manage.py lipeng_export_order_doctor
    create by oldman 2016-12-21
    导出医生的订单
    """

    def handle(self, *args, **options):
        today = datetime.date.today()
        start_day = datetime.date(day=1, month=6, year=today.year)
        end_day = datetime.date(day=1, month=today.month, year=today.year)

        orders = Order.objects.filter(created_time__range=[start_day, end_day], user__doctor__isnull=False)

        dt_result = tablib.Dataset()
        dt_result.headers = [
            u'订单号', u'userID', u'医生ID', u'医生姓名', u'医生所在医院', u'医生关联商务'
        ]

        for order in orders:
            try:
                hospital_name = order.user.doctor.hospital.name if order.user.doctor.hospital else ''
                business_partener = order.user.doctor.business_partener.username if \
                    order.user.doctor.business_partener.username else ''
                dt_result.append([
                    order.id,
                    order.user.id,
                    order.user.doctor.id,
                    order.user.doctor.name,
                    hospital_name,
                    business_partener
                ])
            except Exception as e:
                print e.message
                continue
        open(u'/data/service/doctor_order.xlsx', 'wb').write(dt_result.xlsx)
