# -*- coding: UTF-8 -*-
import tablib
import codecs
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 Service


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_20170428_export_doctor_services
        导出医生美购
    """

    def handle(self, *args, **options):
        wb = load_workbook(filename=u'核心医生组SKUID导出-4.28抽成修正.xlsx')
        sheetnames = wb.get_sheet_names()
        ws = wb.get_sheet_by_name(sheetnames[1])
        error_log = codecs.open('20170428_export_doctor_services_error.txt', 'a', 'utf-8')
        dt_result = tablib.Dataset()
        dt_result.headers = [
            u'美购ID', u'美购名', u'SKUid', u'多属性', u'美购当期医生', u'美购当期医院',
            u'医生id', u'医院id', u'商务', u'更美价', u'预约金', u'抽成',
        ]
        for rx in range(2, ws.get_highest_row() + 1):
            try:
                doctor_id = ws.cell(row=rx, column=2).value
                services = Service.objects.filter(doctor_id=doctor_id, is_online=True)
                for service in services:
                    try:
                        hospital_name = service.doctor.hospital.name
                    except:
                        hospital_name = ''
                    try:
                        business_partner = service.doctor.business_partener.username
                    except:
                        business_partner = ''
                    for item in service.items.filter(is_delete=False):
                        x = (
                            service.id,
                            service.name,
                            item.id,
                            ''.join(item.items_name),
                            service.doctor.name,
                            hospital_name,
                            service.doctor_id,
                            service.doctor.hospital_id,
                            business_partner,
                            item.gengmei_price,
                            item.pre_payment_price,
                            item.discount,
                        )
                        dt_result.append(x)
                    print service.id
            except Exception as e:
                message = u'{}:{}'.format(service.id, e.message)
                print message
                error_log.write(message + u'\n')
                import traceback;
                traceback.print_exc(error_log)
                continue
        get_mail(u'20170428_导出医生美购.xlsx', u'20170428_导出医生美购', [u'chenfeifei@gmei.com'], dt_result.xlsx).send()
        print u'DONE!'
