# -*- coding: UTF-8 -*-
import tablib
import codecs
from openpyxl import load_workbook
from django.core.mail import EmailMessage
from django.core.management import BaseCommand
from django.conf import settings
from api.tasks.export_excel_task import connection
from api.models import Service
from api.models import Doctor
from gm_types.gaia import DOCTOR_TYPE


def get_mail(sub, body, to_user_email, dt):
    mail = EmailMessage(connection=connection)
    mail.from_email = settings.HERA_EMAIL_USER
    mail.subject = sub
    mail.to = to_user_email
    mail.body = body
    mail.attach(sub, dt)
    return mail


class Command(BaseCommand):
    """
        python manage.py dump_20170502_export_doctor_hospital_message
        导出医生机构信息
    """

    def handle(self, *args, **options):
        error_log = codecs.open('20170502_导出医生机构信息.txt', 'a', 'utf-8')

        doctor_result = tablib.Dataset()
        doctor_result.headers = [
            u'医生id', u'医生名称', u'所在机构id', u'所在机构名称', u'医生执业证-照片地址',
            u'医生资格证-照片地址', u'是否有收款信息',
        ]

        hospital_result = tablib.Dataset()
        hospital_result.headers = [
            u'机构管理者ID', u'机构管理者名称', u'所在机构ID', u'所在机构名称',u'营业执照-照片地址',
            u'医疗许可证-照片地址', u'是否有收款信息',
        ]

        doctors = Doctor.objects.all()
        for doctor in doctors:
            try:
                hospital_name = doctor.hospital.name
            except:
                hospital_name = ''
            try:
                x = (
                    doctor.id,
                    doctor.name,
                    doctor.hospital_id,
                    hospital_name,
                    ','.join(doctor.b_licences),
                    ','.join(doctor.p_licences),
                    u'有' if getattr(doctor, 'account', None) else u'无',
                )
                if doctor.doctor_type == DOCTOR_TYPE.DOCTOR:
                    doctor_result.append(x)
                elif doctor.doctor_type == DOCTOR_TYPE.OFFICER:
                    hospital_result.append(x)
                print doctor.id
            except Exception as e:
                message = u'{}:{}'.format(doctor.id, e.message)
                print message
                error_log.write(message + u'\n')
                import traceback;
                traceback.print_exc(error_log)
                continue
        get_mail(u'20170502_导出医生信息.csv', u'20170502_导出医生信息', [u'chenfeifei@gmei.com'], doctor_result.csv).send()
        get_mail(u'20170502_导出机构信息.csv', u'20170502_导出机构信息', [u'chenfeifei@gmei.com'], hospital_result.csv).send()
        print u'DONE!'
