package com.starry.admin.modules.order.listener;

import com.starry.admin.common.exception.CustomException;
import com.starry.admin.modules.order.module.dto.OrderRevocationContext;
import com.starry.admin.modules.order.module.entity.PlayOrderInfoEntity;
import com.starry.admin.modules.order.module.event.OrderRevocationEvent;
import com.starry.admin.modules.withdraw.service.IEarningsService;
import java.math.BigDecimal;
import java.util.Optional;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

@Component
public class OrderRevocationEarningsListener {

    private final IEarningsService earningsService;

    public OrderRevocationEarningsListener(IEarningsService earningsService) {
        this.earningsService = earningsService;
    }

    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
    public void handle(OrderRevocationEvent event) {
        if (event == null || event.getContext() == null || event.getOrderSnapshot() == null) {
            return;
        }
        OrderRevocationContext context = event.getContext();
        if (!context.isDeductClerkEarnings()) {
            return;
        }

        createCounterLine(event);
    }

    private void createCounterLine(OrderRevocationEvent event) {
        OrderRevocationContext context = event.getContext();
        if (context == null) {
            return;
        }
        PlayOrderInfoEntity order = event.getOrderSnapshot();
        String targetClerkId = order.getAcceptBy();
        if (targetClerkId == null || targetClerkId.trim().isEmpty()) {
            throw new CustomException("需要指定收益冲销目标账号");
        }
        BigDecimal amount = context.getEarningsAdjustAmount();
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            amount = Optional.ofNullable(order.getEstimatedRevenue()).orElse(BigDecimal.ZERO);
            if (amount.compareTo(BigDecimal.ZERO) <= 0) {
                return;
            }
        }
        earningsService.createCounterLine(order.getId(), order.getTenantId(), targetClerkId, amount, context.getOperatorId());
    }
}
