#! /usr/bin/env python
# -*- coding: utf-8 -*-
# create by oldman
# Date: 2018/10/12
import tablib
from django.core.management import BaseCommand

from hera.management.commands.utils import get_mail
from hippo.models import MerchantNonsync, DOCTOR_TYPE, Merchant
from hippo.utils import merchant_doctors


class Command(BaseCommand):
    """
    导出不同步的商户的信息
    python manage.py export_2018_10_12_noasync_merchant_doctor
    """

    def handle(self, *args, **options):
        noasyncmerchants = MerchantNonsync.objects.all()
        dt = tablib.Dataset()
        dt.headers = [u'主连锁商户名称', u'名下医生账号名称', u'名下医生账号ID', u'医院名称', u'医院ID', u'是否是商户', u'账户类型']
        for noasyncmerchant in noasyncmerchants:
            try:
                merchant = Merchant.objects.get(id=noasyncmerchant.merchant_id)
                doctor = merchant.doctor
                doctors = merchant_doctors(doctor.id)
                for item in doctors:
                    try:
                        row = (
                            merchant.name,
                            item.name,
                            item.id,
                            item.hospital.name if item.hospital else '',
                            item.hospital.id if item.hospital else '',
                            item.is_merchant,
                            DOCTOR_TYPE.getDesc(item.doctor_type)
                    )
                        dt.append(row)
                    except Exception as e:
                        print e
                        continue
            except Exception as e:
                print e
                continue

        get_mail(u'医生信息.xlsx', u'医生信息.xlsx', u'lipeng@igengmei.com', dt.xlsx).send()