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

change_time = str(datetime.now().date())


class Command(BaseCommand):
    """
        python manage.py dump_20170517_export_doctor_services 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)
        sheetnames = wb.get_sheet_names()
        ws = wb.get_sheet_by_name(sheetnames[1])
        error_message = ''
        dt_result = tablib.Dataset()
        dt_result.headers = [
            u'美购ID', u'美购名', u'SKUid', u'多属性', u'是否手术', u'美购当期医生', u'美购当期医院',
            u'医生id', u'医院id', u'商务', u'更美价', u'预约金', u'抽成',
        ]
        for rx in range(2, ws.get_highest_row() + 1):
            doctor_id = ws.cell(row=rx, column=2).value
            try:
                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),
                            u'是' if service.is_operation else u'否',
                            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 = '{}:{}'.format(doctor_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'{}_error.txt'.format(body), u'{}_error'.format(body), [u'chenfeifei@gmei.com'], error_message).send()
        print u'DONE!'
