# -*- coding: UTF-8 -*-
import tablib
from datetime import datetime
from openpyxl import load_workbook
from django.core.management import BaseCommand
from api.models import ServiceItem
from .utils import get_mail

change_time = datetime.now().strftime('%Y_%m_%d')


class Command(BaseCommand):
    """
        python manage.py dump_20170523_sku_message filename
    """

    def add_arguments(self, parser):
        parser.add_argument('filename', nargs='+', type=str)

    def handle(self, *args, **options):
        filename = options['filename'][0]
        wb = load_workbook(filename=filename)
        ws = wb.active
        error_message = ''
        dt_result = tablib.Dataset()
        dt_result.headers = [
            u'skuid', u'美购id', u'美购名称', u'医生id', u'医生名字', u'商务',
        ]
        for r in ws.rows[1:]:
            sku_id = r[0].value
            try:
                sku = ServiceItem.objects.get(id=sku_id)
                try:
                    business_partner = sku.service.doctor.business_partener.username
                except:
                    business_partner = ''
                x = (
                    sku.id,
                    sku.service_id,
                    sku.service.name,
                    sku.service.doctor_id,
                    sku.service.doctor.name,
                    business_partner,
                )
                dt_result.append(x)
                print sku.id
            except Exception as e:
                message = '{}:{}'.format(sku_id, e.message)
                print message
                error_message += message + '\n'
                continue

        body = u'{}_导出sku信息'.format(change_time)
        get_mail(u'{}.xlsx'.format(body), body, [u'chenfeifei@gmei.com'], dt_result.xlsx).send()
        get_mail(u'{}.csv'.format(body), body, [u'chenfeifei@gmei.com'], dt_result.csv).send()
        get_mail(u'{}_error.txt'.format(body), u'{}_error'.format(body), [u'chenfeifei@gmei.com'], error_message).send()
        print u'DONE!'
