package com.jeesharp.business.modules.pay.route.handler;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.jeesharp.business.modules.pay.combine.dto.PayCombineJsapiRequestDTO;
import com.jeesharp.business.modules.pay.combine.dto.PayCombineSubOrderDTO;
import com.jeesharp.business.modules.pay.combine.dto.PayCombineTransactionResultDTO;
import com.jeesharp.business.modules.pay.combine.support.PayWechatCombineTransactionClient;
import com.jeesharp.business.modules.pay.dto.BasicPayOrderData;
import com.jeesharp.business.modules.pay.route.PayWechatPayRouteContext;
import com.jeesharp.business.modules.pay.route.support.PayWechatJsapiSignSupport;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 合单 JSAPI 预下单（/v3/combine-transactions/jsapi）。
 *
 * @author jeesharp
 * @since 2026-06-12
 */
@Component
@RequiredArgsConstructor
public class CombineJsapiRouteHandler implements PayWechatJsapiRouteHandler {

    private final PayWechatCombineTransactionClient payWechatCombineTransactionClient;

    @Override
    public WxPayUnifiedOrderV3Result.JsapiResult prepay(PayWechatPayRouteContext context, BasicPayOrderData payOrderData)
            throws Exception {
        PayCombineJsapiRequestDTO request = new PayCombineJsapiRequestDTO();
        request.setPlatformTenantId(context.getPlatformTenantId());
        request.setCombineOutTradeNo(payOrderData.getOrderNumber());
        request.setPayerOpenId(payOrderData.getPayerOpenId());
        request.setNotifyUrl(payOrderData.getNotifyUrl());

        List<PayCombineSubOrderDTO> subOrders = new ArrayList<>();
        for (PayWechatPayRouteContext.ResolvedSubPayItem item : context.getSubPayItems()) {
            PayCombineSubOrderDTO sub = new PayCombineSubOrderDTO();
            sub.setMchId(context.getConfig().getMchId());
            sub.setSubMchId(item.getSubMchId());
            sub.setOutTradeNo(StrUtil.blankToDefault(item.getSubOutTradeNo(),
                    payOrderData.getOrderNumber() + "S" + IdUtil.fastSimpleUUID().substring(0, 8)));
            sub.setDescription(StrUtil.blankToDefault(item.getDescription(), payOrderData.getDescription()));
            sub.setTotalAmountFen(item.getAmountFen());
            sub.setProfitSharing(item.isProfitSharing());
            sub.setAttach(StrUtil.blankToDefault(item.getAttach(), payOrderData.getAttach()));
            subOrders.add(sub);
        }
        request.setSubOrders(subOrders);

        PayCombineTransactionResultDTO result = payWechatCombineTransactionClient.jsapiPrepay(request);
        if (!Boolean.TRUE.equals(result.getSuccess())) {
            throw new IllegalStateException("合单 JSAPI 下单失败: " + StrUtil.blankToDefault(result.getErrorMsg(), "未知错误"));
        }
        return PayWechatJsapiSignSupport.signJsapi(context.getConfig(), result.getPrepayId());
    }
}
