# -*- coding: UTF-8 -*-
import tablib
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 SpecialItem
from api.models import ServiceItem
from api.models import DoctorSeckillApply


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_20170508_export_520_sku special_id
        导出专场sku
    """

    def add_arguments(self, parser):
        parser.add_argument('special_id', nargs='+', type=int)

    def handle(self, *args, **options):
        dt_result = tablib.Dataset()
        dt_result.headers = [u'sku_id', u'申请id', u'更美价', u'活动价',  u'预付款', u'抽成', u'自营抽成', u'活动价高于更美价']
        error_log = open('导出专场sku_error.txt', 'a')
        items = SpecialItem.objects.filter(special_id__in=options['special_id']).\
            values('doctorseckillapply_id', 'serviceitem_id').distinct()
        for item in items.iterator():
            apply_id = item['doctorseckillapply_id']
            item_id = item['serviceitem_id']
            try:
                item = ServiceItem.objects.get(id=item_id)
                price_info = item.get_default_price_info()
                gengmei_price = price_info.get('gengmei_price', 0)
                if apply_id:
                    doctor_apply = DoctorSeckillApply.objects.get(id=apply_id)
                    sell_price = doctor_apply.seckill_price
                    pre_payment_price = doctor_apply.pre_payment_price
                    discount = doctor_apply.commission
                else:
                    sell_price = price_info.get('gengmei_price', 0)
                    pre_payment_price = price_info.get('pre_payment_price', 0),
                    discount = price_info.get('discount', 0),

                x = (
                    item_id,
                    apply_id or '',
                    gengmei_price,
                    sell_price,
                    pre_payment_price,
                    discount,
                    price_info.get('self_support_discount', 0),
                    1 if gengmei_price < sell_price else '',
                )
                dt_result.append(x)
                print apply_id, item_id
            except Exception as e:
                message = '{},{}:{}'.format(item_id, apply_id, e.message)
                print message
                error_log.write(message + '\n')
                import traceback;
                traceback.print_exc(error_log)
                continue
        get_mail(u'导出专场sku_resule.xlsx', u'导出{}专场sku_resule'.format(options['special_id']),
                 [u'chenfeifei@gmei.com'], dt_result.xlsx).send()
        print 'DONE!'
