# -*- 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


class Command(BaseCommand):
    """
        python manage.py dump_20170425_export_service_item_lt20
        20元以下在线美购
    """

    def handle(self, *args, **options):
        error_log = codecs.open('20元以下在线美购_error.txt', 'a', 'utf-8')
        services = Service.objects.filter(is_online=True)
        dt_result = tablib.Dataset()
        dt_result.headers = [
            u'美购ID', u'美购名称', u'机构名称', u'负责商务', u'最低多属性价格', u'是否在线',
        ]
        for service in services:
            try:
                price_list = [item.gengmei_price for item in service.items.filter(is_delete=False)]
                min_price = min(price_list) if price_list else None
                if min_price is not None and min_price <= 20:
                    try:
                        hospital_name = service.doctor.hospital.name
                    except:
                        hospital_name = ''
                    try:
                        business_partener = service.doctor.business_partener.username
                    except:
                        business_partener = ''
                    x = (
                        service.id,
                        service.name,
                        hospital_name,
                        business_partener,
                        min_price,
                        u'是' if service.is_online else u'否',
                    )
                    dt_result.append(x)
                    print u'{}:{}'.format(service.id, u'SUCCESS')
                else:
                    print u'{}:{}'.format(service.id, u'FAIL')
            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'20元以下在线美购.xlsx', u'20元以下在线美购', [u'chenfeifei@gmei.com'], dt_result.xlsx).send()
        print u'DONE!'
