# -*- coding: UTF-8 -*-
import tablib
from django.core.management import BaseCommand
from api.models import Service
from gm_types.gaia import HOSPITAL_TYPE
from .utils import get_mail


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

    def handle(self, *args, **options):
        error_message = ''
        dt_result = tablib.Dataset()
        dt_result.headers = [
            u'负责商务', u'美购名称', u'美购ID', u'属性名称', u'属性ID', u'医生', u'医生ID',
            u'医院', u'医院ID', u'是否在线', u'是否自营美购', u'是否手术类', u'更美价', u'预付款',
            u'抽佣金额'
        ]

        services = Service.objects.filter(doctor__hospital__hospital_type=HOSPITAL_TYPE.PUBLIC, is_online=True)
        for service in services.iterator():
            doctor = service.doctor
            hospital = doctor.hospital
            try:
                business = doctor.business_partener.username
            except:
                business = u''

            for item in service.items.filter(is_delete=False):
                try:
                    x = (
                        business,
                        service.name,
                        service.id,
                        ''.join(item.items_name),
                        item.id,
                        doctor.name if doctor else u'',
                        doctor.id if doctor else u'',
                        hospital.name if hospital else u'',
                        hospital.id if hospital else u'',
                        u'在线' if service.is_online else u'否',
                        u'是' if service.is_self_support else u'否',
                        u'是' if service.is_operation else u'否',
                        item.gengmei_price,
                        item.pre_payment_price,
                        item.discount,
                    )
                    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'公立医生美购sku'
        to_email = u'chenfeifei@igengmei.com'
        get_mail(u'{}.xlsx'.format(body), body, to_email, dt_result.xlsx).send()
        get_mail(u'{}.csv'.format(body), body, to_email, dt_result.csv).send()
        get_mail(u'{}_error.txt'.format(body), u'{}_error'.format(body), to_email, error_message).send()
        print u'DONE!'
