# coding=utf-8
import datetime
import json

import xlwt
from django.core.management import BaseCommand
from api.models import OrderExtra, Order
from pay.models import ServiceSnapshot
from rpc.context import get_rpc_remote_invoker


def xlwt_write_row(sheet, row_num, data):
    colum_num = 0
    for o in data:
        sheet.write(row_num, colum_num, o)
        colum_num += 1


class Command(BaseCommand):
    """
    导出霸王餐订单
    python manage.py export_order_1
    """

    def handle(self, *args, **options):

        rpc_invoker = get_rpc_remote_invoker()

        workbook = xlwt.Workbook()
        sheet = workbook.add_sheet('xx')
        header = [u'订单id', u'创建时间', u'spuid', u'美购skuid', u'订单总价(service_price)', u'抽成(discount)', u'快照(pre_payment_price)',
                  u'快照(gengmei_price)',  u'快照(total_price)', u'快照(discount)', u'更美价(gengmei_price)', u'实付金额(total_price)',
                  u'抽成(discount)', u'预付款(pre_payment_price)', u'活动价', u'活动类型', u'活动ID']
        xlwt_write_row(sheet, 0, header)
        row = 1

        start_time = datetime.date.today().replace(day=19)
        order_ids = list(OrderExtra.objects.filter(promotion_type=u'霸王餐').values_list('order_id', flat=True))
        orders = Order.objects.filter(id__in=order_ids, created_time__gte=start_time).order_by('created_time')
        new_order_ids = list(orders.values_list('id', flat=True))

        servicesnapshot = ServiceSnapshot.objects.filter(order_id__in=new_order_ids)
        servicesnapshot_dict = {s.order_id: s for s in servicesnapshot}

        order_id2commodity_commission = rpc_invoker['poseidon/promotion/hera/commodity/commission'](
            order_ids=new_order_ids).unwrap()

        for order in orders:
            order_extra = OrderExtra.objects.get(order=order)
            service_s = servicesnapshot_dict.get(order.id)
            service_snapshot = json.loads(order.service_snapshot)
            commodity_commission = order_id2commodity_commission.get(order.id)
            try:
                sheet.write(row, 0, order.id)
                sheet.write(row, 1, order.created_time.strftime('%Y-%m-%d %H:%M:%S'))
                sheet.write(row, 2, order.service_id)
                sheet.write(row, 3, order.service_item_id)
                sheet.write(row, 4, order.service_price)
                sheet.write(row, 5, order.discount)
                sheet.write(row, 6, service_snapshot["pre_payment_price"])
                sheet.write(row, 7, service_snapshot["gengmei_price"])
                sheet.write(row, 8, service_snapshot["total_price"])
                sheet.write(row, 9, service_snapshot["discount"])
                sheet.write(row, 10, service_s.gengmei_price)
                sheet.write(row, 11, service_s.total_price)
                sheet.write(row, 12, service_s.discount)
                sheet.write(row, 13, service_s.pre_payment_price)
                sheet.write(row, 14, commodity_commission.get("activity_price", "NO_DATA"))
                sheet.write(row, 15, order_extra.promotion_type)
                sheet.write(row, 16, order_extra.promotion_id)
                row += 1
            except Exception as e:
                row += 1
                print e.message
                print ('异常订单id{}'.format(order.id))
                continue
        print u'结束'

        workbook.save(u'霸王餐订单信息.xls')
