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



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

    def handle(self, *args, **options):
        filename_list = [u'预热改8折的商品列表.xlsx', u'预热改9折的商品列表.xlsx']
        for filename in filename_list:
            wb = load_workbook(filename=filename)
            sheetnames = wb.get_sheet_names()
            ws = wb.get_sheet_by_name(sheetnames[0])
            error_log = open(u'{}_error.txt'.format(filename), 'a')
            dt_result = tablib.Dataset()
            dt_result.headers = [u'sku_id', u'申请id', u'更美价', u'预付款', u'抽成']
            for rx in range(2, ws.get_highest_row() + 1):
                sku_id = int(ws.cell(row=rx, column=1).value)
                try:
                    sku = ServiceItem.objects.get(id=sku_id)
                    price_info = sku.get_default_price_info()
                    x = (
                        sku.id,
                        '',
                        price_info.get('gengmei_price', 0),
                        price_info.get('pre_payment_price', 0),
                        price_info.get('discount', 0),
                    )
                    dt_result.append(x)
                    print sku.id
                except Exception as e:
                    message = '{}:{}'.format(sku_id, e.message)
                    print message
                    error_log.write(message + u'\n')
                    import traceback;
                    traceback.print_exc(error_log)
                    continue
            get_mail(u'{}_result.xlsx'.format(filename), u'{}_result'.format(filename),
                     [u'chenfeifei@gmei.com'], dt_result.xlsx).send()
            print u'====={}======IS======DONE===='.format(filename)
        print u'DONE!'
