# coding=utf-8
from django.core.management.base import NoArgsCommand
from django.conf import settings

from gm_types.gaia import ORDER_OPERATION_TYPE, ORDER_OPERATION_ROLE
from api.models import Order, Person
from api.models import RefundOrder
from api.models import ORDER_STATUS
from api.models import REFUND_STATUS
from django.db import transaction

order_list = [
]


class Command(NoArgsCommand):
    def handle(self, *args, **options):
        operator = Person.objects.get(user_id=settings.BOSS)

        for one_order in order_list:
            print "order %s ............" % one_order

            order_refunded = False

            with transaction.atomic():
                order = Order.objects.select_for_update().get(pk=one_order)

                try:
                    refund_order = RefundOrder.objects.select_for_update().get(order=order)
                except RefundOrder.DoesNotExist:
                    raise

                # order.status = ORDER_STATUS.WAIT_REFUNDED
                # refund_order.status = REFUND_STATUS.ARBITING
                if order.status == ORDER_STATUS.REFUNDED or refund_order.status == REFUND_STATUS.REFUNDED:
                    print ("status error ! order.status: {}, refund_order.status: {}".format(
                        order.status, refund_order.status)
                    )
                    continue

                print "order.status, before: %s, after: %s" % (order.status, ORDER_STATUS.REFUNDED)
                print "refund_order.status, before: %s, after: %s" % (refund_order.status, REFUND_STATUS.REFUNDED)

                order.operate(operator, ORDER_OPERATION_TYPE.REFUNDED, ORDER_OPERATION_ROLE.SYSTEM)
                order_refunded = True

            if order_refunded is True:
                from api.tool.order_tool import send_momo_stat_log_info_when_order_refunded
                send_momo_stat_log_info_when_order_refunded(order)
