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

from django.db import transaction
from gm_types.trade import SETTLEMENT_PAY_MODE
from gm_types.gaia import POINTS_TYPE

import point
from api.models import SETTLEMENT_STATUS, Settlement, CouponInfo


def cancel_settlement(settlement, cancel_reason):
    from api.manager.order_manager import cancel_order

    with transaction.atomic():
        old_settlement = settlement

        settlement = Settlement.objects.select_for_update().get(id=old_settlement.id)

        if settlement.status in [SETTLEMENT_STATUS.NOT_PAID, SETTLEMENT_STATUS.PAYING]:

            coupon_info_ids = settlement.get_coupon_info_ids()
            if coupon_info_ids:
                coupon_infos = CouponInfo.objects.filter(id__in=coupon_info_ids)
                for ci in coupon_infos:
                    if ci.can_be_returned():
                        ci.return_coupon()

            orders = [i.order for i in settlement.items.all()]
            # 按照service_item_id的次序取消订单，主要是避免潜在的数据库死锁
            sorted_orders = sorted(orders, key=lambda o: o.service_item_id)

            for order in sorted_orders:
                cancel_order(order)

                # return points
                points_used_amount = order.points_deduction * 100 or order.points
                point.add(
                    user_id=settlement.person.user.id,
                    reason=POINTS_TYPE.CANCEL_ORDER,
                    point=points_used_amount,
                    order_id=order.id,
                )

            # update settlement status
            settlement.status = SETTLEMENT_STATUS.CANCEL
            settlement.cancel_reason = cancel_reason
            settlement.save()

            if settlement.pay_mode == SETTLEMENT_PAY_MODE.INSTALLMENT:
                order_id = settlement.items.first().order_id
                from rpc.context import create_fake_context
                ctx = create_fake_context()
                ctx.gaia_local['pay/installment/refund'](partner=1, order_id=order_id).unwrap()
