# coding=utf-8
# create by oldman at 2018/2/7
import tablib
from django.core.management import BaseCommand

from hera.management.commands.utils import get_mail
from hippo.models import Doctor
from hippo.models import MerchantRelevance
from themis.models import Team


class Command(BaseCommand):
    """
    导出医生的信息(姓名，ID，医院，医院ID，商户，商户医生ID，商务，商务组)
    python manage.py export_2018_02_07_doctor_merchant_info
    """

    def handle(self, *args, **options):
        doctors = Doctor.objects.all()
        count = doctors.count()
        begin = 0
        step = 1000
        print count
        dt = tablib.Dataset()
        dt.headers = [u'医生ID', u'医生名字', u'医院ID', u'医院名', u'商户ID', u'商户对应医生ID', u'商务', u'商务组']
        while begin <= count:
            for doctor in doctors[begin:begin + step]:
                print doctor.id
                try:
                    merchantrelevances = MerchantRelevance.objects.filter(merchant__is_online=True,
                                                                          doctor=doctor)
                    try:
                        hospital = doctor.hospital
                    except:
                        hospital = None
                    try:
                        merchant = merchantrelevances.first().merchant
                    except:
                        merchant = None

                    try:
                        team = Team.objects.get(id=doctor.business_group).name
                    except:
                        team = u''

                    row = (
                        doctor.id,
                        doctor.name,
                        hospital.id if hospital else u'',
                        hospital.name if hospital else u'',
                        merchant.id if merchant else u'',
                        merchant.doctor.id if merchant else u'',
                        doctor.business_partener.username if doctor.business_partener else u'',
                        team,
                    )
                    dt.append(row)
                except Exception as e:
                    print e.message
                    continue

            begin += step
        body = u'医生信息'
        get_mail(u'医生信息.xlsx', u'医生信息.xlsx', u'lipeng@igengmei.com', dt.xlsx).send()
        get_mail(u'医生信息.csv', u'医生信息.csv', u'lipeng@igengmei.com', dt.csv).send()
