# -*- coding: UTF-8 -*-
import tablib
from django.core.mail import EmailMessage
from django.core.management import BaseCommand
from django.conf import settings
from django.db.models import Count
from api.tasks.export_excel_task import connection
from api.models import Order
from api.models import ServiceItem


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_20170331_export_service_item_count
        导出医生账户信息
    """

    def handle(self, *args, **options):
        orders = Order.objects.filter(pay_time__range=['2017-03-01', '2017-04-01']).values('service_item_id').annotate(count=Count('service_item_id')).order_by('-count')[:500]
        dt_error = tablib.Dataset()
        dt_result = tablib.Dataset()
        dt_result.headers = [
            u'item', u'sku-id', u'商品名称', u'所属医院－医生', u'总价', u'预付款', u'尾款',
            u'商品线上链接', u'竞对商品链接'
        ]
        idx = 0
        for order in orders:
            idx += 1
            try:
                item = ServiceItem.objects.get(id=order['service_item_id'])
                hospital_name = item.service.doctor.hospital.name if item.service.doctor.hospital_id else ''
                x = (
                    idx,
                    item.id,
                    u'{}+{}'.format(item.service.name, u''.join(item.items_name)),
                    u'{}-{}'.format(item.service.doctor.name, hospital_name),
                    item.get_default_price_info()['gengmei_price'],
                    item.get_default_price_info()['pre_payment_price'],
                    item.get_default_price_info()['gengmei_price'] - item.get_default_price_info()['pre_payment_price'],
                    u'http://www.gmei.com/promotion/{}/'.format(item.service_id),
                    u'',
                )
                dt_result.append(x)
                print order['service_item_id']
            except Exception as e:
                print order['service_item_id'], e.message
                dt_error.append((order['service_item_id'], e.message))
        get_mail(u'线上sku成交量导出.xlsx', u'线上sku成交量导出', [u'chenfeifei@gmei.com'], dt_result.xlsx).send()
        get_mail(u'线上sku成交量导出_error.xlsx', u'线上sku成交量导出_error', [u'chenfeifei@gmei.com'], dt_error.xlsx).send()
        print 'DONE!'
