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

import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.jeesharp.business.modules.pay.dto.BasicPayOrderData;
import com.jeesharp.business.modules.pay.route.PayWechatPayRouteContext;
import com.jeesharp.business.modules.pay.service.weixin.PayWechatV3UnifiedOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 境内直连 JSAPI 预下单（/v3/pay/transactions/jsapi）；忽略 L2 分账打标。
 *
 * @author jeesharp
 * @since 2026-06-12
 */
@Component
@RequiredArgsConstructor
public class DirectJsapiRouteHandler implements PayWechatJsapiRouteHandler {

    private final PayWechatV3UnifiedOrderService payWechatV3UnifiedOrderService;

    @Override
    public WxPayUnifiedOrderV3Result.JsapiResult prepay(PayWechatPayRouteContext context, BasicPayOrderData payOrderData)
            throws Exception {
        BasicPayOrderData directData = copyWithoutProfitSharing(payOrderData);
        Object raw = payWechatV3UnifiedOrderService.createOrder(directData);
        if (raw instanceof WxPayUnifiedOrderV3Result.JsapiResult jsapi) {
            return jsapi;
        }
        throw new IllegalStateException("微信 V3 返回类型非 JSAPI: " + (raw == null ? "null" : raw.getClass().getName()));
    }

    private static BasicPayOrderData copyWithoutProfitSharing(BasicPayOrderData source) {
        BasicPayOrderData copy = new BasicPayOrderData();
        copy.setPayType(source.getPayType());
        copy.setUserId(source.getUserId());
        copy.setCompanyId(source.getCompanyId());
        copy.setPayAmount(source.getPayAmount());
        copy.setOrderNumber(source.getOrderNumber());
        copy.setSubject(source.getSubject());
        copy.setDescription(source.getDescription());
        copy.setNotifyUrl(source.getNotifyUrl());
        copy.setAttach(source.getAttach());
        copy.setPayerOpenId(source.getPayerOpenId());
        copy.setWxTradeType(source.getWxTradeType());
        copy.setBizScene(source.getBizScene());
        copy.setBizOrderId(source.getBizOrderId());
        copy.setFinancePayOrderId(source.getFinancePayOrderId());
        copy.setTenantId(source.getTenantId());
        copy.setNeedProfitSharing(false);
        return copy;
    }
}
