package com.jeesharp.business.modules.finance.settle.support;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.finance.api.dto.PaySettleBizOrderSnapshot;
import com.jeesharp.business.modules.finance.payorder.entity.PayOrder;
import com.jeesharp.business.modules.finance.payorder.service.PayOrderService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * 无专属 Provider 的业态兜底：按财务支付单解析单笔子单摘要（酒店/美食等 1 单 1 付，无合并批次）。
 *
 * @author jeesharp
 * @since 2026-06-11
 */
@Component
@AllArgsConstructor
public class GenericPaySettleBizOrderProvider {

    private final PayOrderService payOrderService;

    public PaySettleBizOrderSnapshot getOrder(String bizScene, String bizOrderId) {
        PayOrder payOrder = findSuccessPayOrder(bizScene, bizOrderId);
        if (payOrder == null) {
            return null;
        }
        return toSnapshot(bizOrderId, payOrder);
    }

    public List<PaySettleBizOrderSnapshot> listSubOrdersForPay(String bizScene, String payBatchId, String bizOrderId) {
        String key = StrUtil.isNotBlank(payBatchId) ? payBatchId : bizOrderId;
        PaySettleBizOrderSnapshot single = getOrder(bizScene, key);
        return single != null ? List.of(single) : Collections.emptyList();
    }

    private PayOrder findSuccessPayOrder(String bizScene, String bizOrderId) {
        if (StrUtil.isBlank(bizOrderId) || StrUtil.isBlank(bizScene)) {
            return null;
        }
        return payOrderService.findLatestSuccessByBiz(bizOrderId.trim(), bizScene);
    }

    private static PaySettleBizOrderSnapshot toSnapshot(String bizOrderId, PayOrder payOrder) {
        PaySettleBizOrderSnapshot snapshot = new PaySettleBizOrderSnapshot();
        snapshot.setBizOrderId(bizOrderId);
        snapshot.setTenantId(payOrder.getTenantId());
        snapshot.setPayAmount(payOrder.getPayAmount());
        snapshot.setTotalAmount(payOrder.getPayAmount());
        snapshot.setPayBatchId(bizOrderId);
        return snapshot;
    }
}
