# coding=utf-8

from django.core.management.base import NoArgsCommand
from django.conf import settings
from django.db import transaction

from gm_types.gaia import ORDER_OPERATION_ROLE, ORDER_OPERATION_TYPE

from api.models import Order, Person, RefundOrder
from api.models import ORDER_STATUS, REFUND_STATUS
from api.manager import order_manager

order_list = [

]

def deal_have_refund_orders(order_list):
    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)


def deal_not_have_refund_orders(order_list):
    for one_order in order_list:
        with transaction.atomic():
            order = Order.objects.select_for_update().get(pk=one_order)
            print 'order %s , status : %s ... ' % (
            str(one_order), str(order.status))
            order_manager.refund_can_not_refundorder(order)
            print 'order ok %s ..' % one_order


class Command(NoArgsCommand):
    """
    python manage.py zmz_deal_all_refund
    """
    def handle(self, *args, **options):

        have_refund = lambda order_id: RefundOrder.objects.filter(order_id=order_id).exists()

        have_refund_order_list = list(RefundOrder.objects.filter(
            order_id__in=order_list).values_list('order_id', flat=True))

        not_have_refund_order_list = list(set(order_list) - set(have_refund_order_list))

        deal_have_refund_orders(have_refund_order_list)
        deal_not_have_refund_orders(not_have_refund_order_list)
        print('Done!')

