# -*- 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
from api.models import Service

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


class Command(BaseCommand):
    """
        python manage.py dump_20170609_service_message
    """

    def handle(self, *args, **options):
        error_message = ''
        dt_result = tablib.Dataset()
        dt_result.headers = [
            u'美购ID', u'美购名称', u'属性ID',u'属性名称', u'更美价',
            u'抽成', u'医生id', u'医生',u'医院ID', u'医院', u'商务',
        ]
        services = Service.objects.filter(is_online=True)
        for service in services.iterator():
            try:
                business_partener = service.doctor.business_partener.username
            except:
                business_partener = ''

            for item in service.items.filter(is_delete=False):
                try:
                    price_info = item.get_default_price_info()
                    x = (
                        service.id,
                        service.name,
                        item.id,
                        ''.join(item.items_name),
                        price_info['gengmei_price'],
                        price_info['discount'],
                        service.doctor_id,
                        service.doctor.name,
                        service.doctor.hospital_id,
                        service.doctor.hospital.name,
                        business_partener,
                    )
                    dt_result.append(x)
                    print service.id, item.id
                except Exception as e:
                    message = '{},{},{}'.format(service.id, item.id, e.message)
                    print message
                    error_message += message + '\n'
                    continue

        body = u'{}_导出美购信息'.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!'
