# coding=utf-8
# create by oldman at 17/2/19
import tablib
from django.core.management import BaseCommand
from django.db.models import F

from api.models import ServiceItem, ServiceItemPrice


class Command(BaseCommand):
    """
    导出当前时间在线且预付款小于抽成金额的美购
    python manage.py dump_20170219_serviceitem_data_prepayment_lt_discount
    """

    def handle(self, *args, **options):
        skuprinces = ServiceItemPrice.objects.filter(service_item__service__is_online=True,
                                                     service_item__is_delete=False,
                                                     is_default_price=True,
                                                     pre_payment_price__lt=F('discount'))


        dt_result = tablib.Dataset()
        dt_result.headers = [u'skuID', u'属性名称', u'美购ID', u'美购名称', u'预付款金额', u'抽成金额', u'更美价', u'医生ID',
                             u'医生名称', u'医院ID', u'医院名称', u'关联商务', u'商务所在组']
        for skuprince in skuprinces:
            print skuprince.service_item.id
            try:
                try:
                    group = ','.join([item.title for item in
                                      skuprince.service_item.service.doctor.business_partener.belong_groups.all()])
                except:
                    group = ''
                x = (
                    skuprince.service_item.id,
                    ''.join(skuprince.service_item.items_name),
                    skuprince.service_item.service.id,
                    skuprince.service_item.service.name,
                    skuprince.pre_payment_price,
                    skuprince.discount,
                    skuprince.gengmei_price,
                    skuprince.service_item.service.doctor.id,
                    skuprince.service_item.service.doctor.name,
                    skuprince.service_item.service.doctor.hospital.id,
                    skuprince.service_item.service.doctor.hospital.name,
                    skuprince.service_item.service.doctor.business_partener.username,
                    group
                )
                dt_result.append(x)
            except Exception as e:
                print e.message
                continue
        open('/data/service/serviceitem_prepayment.xlsx', 'wb').write(dt_result.xlsx)
        print('Done')
