# coding=utf-8
import tablib
from django.core.management import BaseCommand

from api.models import Order


class Command(BaseCommand):
    """
    python manage.py dump_20161223_export_settlement_data
    导出9，10，11月份结算单数据
    """

    def handle(self, *args, **options):
        orders = Order.objects.filter(statement__statement_date__in=[201609, 201610, 201611])
        dt_result = tablib.Dataset()
        dt_result.headers = [u'结算周期', u'结算对象ID', u'结算对象名称', u'订单号', u'使用的美券ID', u'美券抵扣',
                             u'美分抵扣', u'应结预付款', u'结算状态']
        for obj in orders:
            try:
                statement = obj.statement.first()
                temp = (statement.statement_date, statement.doctor.id, statement.doctor.name,
                        obj.id, obj.settlementitem.settlement.coupon.coupon.id if obj.settlementitem.settlement.coupon
                        else u'',
                        obj.coupon_deduction, obj.points_deduction,
                        obj.servicesnapshot.pre_payment_price - obj.discount,
                        u'已结算' if obj.is_settled else u'未结算')
                dt_result.append(temp)
            except Exception as e:
                print e.message
                continue
        open('/data/service/settlements.xlsx', 'wb').write(dt_result.xlsx)
