# coding=utf-8
import tablib
from django.core.management import BaseCommand
from django.core.mail import EmailMessage
from django.conf import settings
from api.models import Shopcart
from api.models import ServiceItem
from api.tasks.export_excel_task import connection


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_20170327_shopcart_item_price
    """

    def handle(self, *args, **options):
        file = open('/tmp/20170216-20170316加入购物车未购买用户_购物车ID.txt', 'r')
        lines = file.read().split('\r')
        error_result = tablib.Dataset()
        dt = tablib.Dataset()
        dt.headers = [u'id', u'美购id', u'sku_id', u'sku_name', u'更美价', u'是否下线']
        for shopcart_id in lines:
            try:
                shopcart = Shopcart.objects.get(id=int(shopcart_id))
                if shopcart.service_item_key:
                    service_item = ServiceItem.objects.filter(parent_id=0, service=shopcart.service, key=shopcart.service_item_key)[0]
                else:
                    service_item = shopcart.service.items.all()[0]
                x = (
                    shopcart.id,
                    shopcart.service_id,
                    service_item.id,
                    ''.join(service_item.items_name),
                    service_item.gengmei_price,
                    u'是' if service_item.is_delete else u'否'
                )
                dt.append(x)
                print shopcart.id
            except Exception as e:
                message = u'{}:{}'.format(shopcart_id, e.message)
                print message
                error_result.append((shopcart_id, e.message))
        get_mail(u'20170316加入购物车未购买用户_sku价格.xlsx', u'20170316加入购物车未购买用户_sku价格', [u'chenfeifei@gmei.com', u'yilingxiao@gmei.com'], dt.xlsx).send()
        get_mail(u'20170316加入购物车未购买用户_sku价格_error.csv', u'20170316加入购物车未购买用户_sku价格_error', [u'chenfeifei@gmei.com'], error_result.csv).send()
        print 'DONE!'
