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

import cn.hutool.core.util.StrUtil;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.jeesharp.business.modules.pay.dto.BasicPayOrderData;
import com.jeesharp.business.modules.pay.partner.dto.PayPartnerJsapiRequestDTO;
import com.jeesharp.business.modules.pay.partner.dto.PayPartnerTransactionResultDTO;
import com.jeesharp.business.modules.pay.partner.support.PayWechatPartnerTransactionClient;
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;

/**
 * partner 单商户 JSAPI 预下单（/v3/pay/partner/transactions/jsapi）。
 *
 * @author jeesharp
 * @since 2026-06-12
 */
@Component
@RequiredArgsConstructor
public class PartnerJsapiRouteHandler implements PayWechatJsapiRouteHandler {

    private final PayWechatPartnerTransactionClient payWechatPartnerTransactionClient;

    @Override
    public WxPayUnifiedOrderV3Result.JsapiResult prepay(PayWechatPayRouteContext context, BasicPayOrderData payOrderData)
            throws Exception {
        if (context.getSubPayItems() == null || context.getSubPayItems().isEmpty()) {
            throw new IllegalStateException("partner 单商户下单缺少子商户信息");
        }
        PayWechatPayRouteContext.ResolvedSubPayItem sub = context.getSubPayItems().get(0);
        PayPartnerJsapiRequestDTO request = new PayPartnerJsapiRequestDTO();
        request.setPlatformTenantId(context.getPlatformTenantId());
        request.setSubMchId(sub.getSubMchId());
        request.setOutTradeNo(payOrderData.getOrderNumber());
        request.setDescription(StrUtil.blankToDefault(sub.getDescription(), payOrderData.getDescription()));
        request.setTotalAmountFen(sub.getAmountFen());
        request.setPayerOpenId(payOrderData.getPayerOpenId());
        request.setNotifyUrl(payOrderData.getNotifyUrl());
        request.setAttach(StrUtil.blankToDefault(sub.getAttach(), payOrderData.getAttach()));
        request.setProfitSharing(sub.isProfitSharing());

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