package com.jeesharp.business.pay.support;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.jeesharp.business.modules.food.vo.FoodPersonalMealPayPrepareVO;
import com.jeesharp.business.modules.pay.vo.WechatJsapiPrepayVO;
import com.jeesharp.business.pay.model.WechatJsapiPrepayResult;
import com.jeesharp.business.pay.model.WechatPrepayOutcome;

/**
 * 支付中心 {@link WechatJsapiPrepayVO} 与网关 {@link WechatJsapiPrepayResult} 互转。
 *
 * @author jeesharp
 * @since 2026-05-25
 */
public final class WechatJsapiPrepayVoMapper {

    private WechatJsapiPrepayVoMapper() {
    }

    public static WechatJsapiPrepayResult toGatewayResult(WechatJsapiPrepayVO vo) {
        if (vo == null) {
            return null;
        }
        WechatJsapiPrepayResult r = new WechatJsapiPrepayResult();
        r.setMock(vo.isMock());
        r.setAppId(vo.getAppId());
        r.setTimeStamp(vo.getTimeStamp());
        r.setNonceStr(vo.getNonceStr());
        r.setPackageValue(vo.getPackageValue());
        r.setSignType(vo.getSignType());
        r.setPaySign(vo.getPaySign());
        r.setPrepayId(vo.getPrepayId());
        return r;
    }

    /**
     * 将微信预支付编排结果写回各业态预支付 VO（字段名对齐：outTradeNo、payerOpenId 及 JSAPI 调起参数）。
     */
    public static void applyPrepareOutcome(Object vo, WechatPrepayOutcome outcome) {
        if (vo == null || outcome == null) {
            return;
        }
        BeanUtil.setFieldValue(vo, "outTradeNo", outcome.getOutTradeNo());
        BeanUtil.setFieldValue(vo, "payerOpenId", outcome.getPayerOpenId());
        if (vo instanceof FoodPersonalMealPayPrepareVO mealVo) {
            mealVo.setPayOrderId(outcome.getFinancePayOrderId());
        }
        copyJsapiClientFields(outcome.getPayResult(), vo);
    }

    private static void copyJsapiClientFields(WechatJsapiPrepayResult payResult, Object targetVo) {
        if (payResult == null || targetVo == null) {
            return;
        }
        BeanUtil.copyProperties(payResult, targetVo, CopyOptions.create());
    }
}
