# -*- coding: UTF-8 -*-
import tablib
from django.core.management import BaseCommand
from hippo.models import DoctorAccount
from gm_types.gaia import HOSPITAL_TYPE
from .utils import get_mail


class Command(BaseCommand):
    """
        python manage.py dump_20170710_public_doctor_account
    """

    def handle(self, *args, **options):
        error_message = ''
        dt_result = tablib.Dataset()
        dt_result.headers = [
            u'医生ID', u'医生名', u'医院ID', u'医院名', u'户名', u'账号'
        ]
        accounts = DoctorAccount.objects.filter(doctor__hospital__hospital_type=HOSPITAL_TYPE.PUBLIC)
        for account in accounts.iterator():
            try:
                x = (
                    account.doctor_id,
                    account.doctor.name,
                    account.doctor.hospital_id,
                    account.doctor.hospital.name,
                    account.account_name,
                    u' {}'.format(account.account_number),
                )
                dt_result.append(x)
                print account.id
            except Exception as e:
                message = '{},{}'.format(account.id, e.message)
                print message
                error_message += message + '\n'
                continue
        body = u'公立医生打款账户'
        to_email = u'chenfeifei@gmei.com'
        get_mail(u'{}.xlsx'.format(body), body, to_email, dt_result.xlsx).send()
        get_mail(u'{}.csv'.format(body), body, to_email, dt_result.csv).send()
        get_mail(u'{}_error.txt'.format(body), u'{}_error'.format(body), u'chenfeifei@gmei.com', error_message).send()
        print u'DONE!'
