# -*- coding: UTF-8 -*-
import tablib
import codecs
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


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

doctor_ids = [
    'aojianfei',
    'liuzhenjun',
    'yinhongyu',
    'xieyangchun',
    'xujiajie',
    'liujianfeng',
    'dutaichao',
    '03e55f96ccdf11e6940500163e0051d4',
    'chenxiaofang',
    'zhouchangqing',
    'yuhongmin',
    'matao',
    'xuguang',
    'xulianji',
    'songchunqiong',
    'd43c88f694ee11e5976500163e002fb3',
    'qiaosong',
    'wangruiheng',
    'DRzhangjie',
    '3cc9017e32a611e6821f00163e0051d4',
    'caixiangnuo',
    'chengang',
    'lichang',
    'liujinyuan',
]


class Command(BaseCommand):
    """
        python manage.py dump_20170426_export_doctor_serivices
        导出医生美购
    """

    def handle(self, *args, **options):
        error_log = codecs.open('export_doctor_serivices_error.txt', 'a', 'utf-8')
        dt_result = tablib.Dataset()
        dt_result.headers = [
            u'医生id', u'医生名称', u'所属机构', u'美购ID', u'美购名称', u'skuid',
            u'sku名称', u'更美价', u'上下线状态', u'美购开始时间', u'美购结束时间',
            u'预付款比例', u'预付款金额',
        ]
        services = Service.objects.filter(doctor_id__in=doctor_ids)
        for service in services:
            try:
                try:
                    hospital_name = service.doctor.hospital.name
                except:
                    hospital_name = ''
                for item in service.items.filter(is_delete=False):
                    x = (
                        service.doctor_id,
                        service.doctor.name,
                        hospital_name,
                        service.id,
                        service.name,
                        item.id,
                        ''.join(item.items_name),
                        item.gengmei_price,
                        u'上线' if service.is_online else u'下线',
                        str(service.start_time or ''),
                        str(service.end_time or ''),
                        u'{}%'.format(item.pre_payment_price * 100/item.gengmei_price),
                        item.pre_payment_price,
                    )
                    dt_result.append(x)
                print service.id
            except Exception as e:
                message = u'{}:{}'.format(service.id, e.message)
                print message
                error_log.write(message + u'\n')
                import traceback;
                traceback.print_exc(error_log)
                continue
        get_mail(u'导出医生美购.xlsx', u'导出医生美购', [u'chenfeifei@gmei.com'], dt_result.xlsx).send()
        print u'DONE!'
