# coding=utf-8
from api.models import Order
from rpc.context import get_rpc_remote_invoker
from rpc.decorators import bind_context
from api.manager.refund_manager import increase_inventory
from gm_types.gaia import PAYMENT_CHANNEL

from rpc.tool.log_tool import logging_exception
from rpc.tool.error_code import gen, CODES


@bind_context("pay/unified/cashback", login_required=True)
def pay_unified_cashback(ctx, order_id):
    order = Order.objects.get(pk=order_id)
    if order.payment_channel == PAYMENT_CHANNEL.ALIPAY:
        return ctx.gaia_local['pay/alipay/cashback/new'](order_id=order_id).unwrap()
    if order.payment_channel == PAYMENT_CHANNEL.WECHAT:
        return ctx.gaia_local['pay/wechat/cashback/new'](order_id=order_id).unwrap()
    if order.payment_channel == PAYMENT_CHANNEL.APPLEPAY:
        return ctx.gaia_local['pay/apple/cashback'](order_id=order_id).unwrap()


@bind_context("pay/unified/refund")
def pay_unified_refund(ctx, order_id):
    order = Order.objects.get(pk=order_id)

    # 该订单不能退款
    if not order.refund_anytime:
        gen(CODES.ORDER_CAN_NOT_REFUND)

    # 发起退款网关之前, 释放库存
    try:
        increase_inventory(order)
    except:
        pass

    # 尝试先去退款任买订单 无论是什么状态均认为退款成功
    try:
        get_rpc_remote_invoker()['plutus/installment/user/abandon'](person_id=order.user.person.id.hex,
                                                                    order_id=order.id).unwrap()
    except:
        pass

    if order.payment_channel == PAYMENT_CHANNEL.ALIPAY:
        return ctx.gaia_local['pay/alipay/refund/new'](order_id=order_id).unwrap()
    if order.payment_channel == PAYMENT_CHANNEL.WECHAT:
        return ctx.gaia_local['pay/wechat/refund/new'](order_id=order_id).unwrap()
    if order.payment_channel == PAYMENT_CHANNEL.APPLEPAY:
        return ctx.gaia_local['pay/apple/refund'](order_id=order_id).unwrap()
    if order.payment_channel == PAYMENT_CHANNEL.XIAOYING:
        return ctx.gaia_local['pay/installment/refund'](partner=1, order_id=order_id).unwrap()
