# coding=utf-8
from __future__ import unicode_literals, absolute_import

from celery import shared_task
from django.conf import settings

from api.models.user import User
from api.models.types import ORDER_OPERATION_TYPE
from api.models.types import ORDER_OPERATION_ROLE
from api.tool.log_tool import logging_exception
from api.models import RefundOrder
from api.models import CashBackOrder
from gm_types.gaia import REFUND_STATUS
from gm_types.gaia import NEW_CASH_BACK_STATUS


def _refund(ctx, order, operator):
    try:
        # order.operate(operator, ORDER_OPERATION_TYPE.LOW_BALANCE, ORDER_OPERATION_ROLE.SYSTEM)
        ctx.gaia_local['pay/unified/refund'](order_id=order.id).unwrap()
    except:
        logging_exception()


@shared_task
def apple_pay_refund():
    from rpc.context import create_fake_context
    ctx = create_fake_context()
    system_user = User.objects.get(pk=settings.BOSS)
    operator = system_user.person

    status_can_be_refunded = [REFUND_STATUS.REFUND_APPLY_SELLER_TIMEOUT, REFUND_STATUS.DOCTOR_APPROVE]
    for refund in RefundOrder.objects.filter(low_balance=True).filter(status__in=status_can_be_refunded):
        _refund(ctx, refund.order, operator)

    for cashback in CashBackOrder.objects.filter(low_balance=True).filter(status=NEW_CASH_BACK_STATUS.WAIT):
        _refund(ctx, cashback.order, operator)
