# coding=utf-8
from django.core.management.base import NoArgsCommand
from django.db import transaction
from api.models.order import REFUND_STATUS
from api.models.order import CASH_BACK_STATUS
from api.models.order import Order
from api.models.order import ORDER_STATUS
from api.models.order import RefundOrder
from api.models.order import CashBackOrder


class Command(NoArgsCommand):
    def handle(self, *args, **options):
        # 对于老退款订单, 状态为等待退款, 且无新退款单, 直接生成退款单
        # 并将退款单状态改为申请仲裁, 交给运营处理
        wati_refund_orders = Order.objects.filter(status=ORDER_STATUS.WAIT_REFUNDED, refund__isnull=True)
        for order in wati_refund_orders:
            refund_order = RefundOrder.create(order, order.refund_comment)
            refund_order.status = REFUND_STATUS.ARBITING
            refund_order.save()
            print "create RefundOrder refund_order_id: {refund_order_id}\t order_id: {order_id} refunder status is {status}".format(
                refund_order_id=refund_order.id,
                order_id=refund_order.order_id,
                status=refund_order.status
            )

        # 对于老返现订单, 返现状态为等待返现, 且无新返现单, 直接生成返现单
        # 并将返现单状态变为, 等待返现
        wati_cashback_orders = Order.objects.filter(cash_back_status=CASH_BACK_STATUS.WAIT, cashback__isnull=True)
        for order in wati_cashback_orders:
            # 老的返现, 自动变成返现等待
            cashback_order = CashBackOrder.create(order)
            print "create CashbackOrder cashback_order_id: {cashback_order_id}\t order_id: {order_id} cashback status is {status}".format(
                cashback_order_id=cashback_order.id,
                order_id=cashback_order.order_id,
                status=cashback_order.status
            )
