package org.dromara.pay.util;

import com.wechat.pay.java.core.cipher.RSASigner;
import java.security.PrivateKey;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 微信支付 V3 工具类
 *
 * @author pengles
 */
public class WechatPayUtil {

    /**
     * App 支付二次签名
     *
     * @param appId       应用ID
     * @param mchId       商户ID
     * @param prepayId    预支付交易会话ID
     * @param privateKey  商户私钥
     * @param mchSerialNo 商户API证书序列号
     * @return 返回给 App 的参数
     */
    public static Map<String, String> signApp(String appId, String mchId, String prepayId, PrivateKey privateKey, String mchSerialNo) {
        long timestamp = Instant.now().getEpochSecond();
        String nonceStr = UUID.randomUUID().toString().replace("-", "");
        String message = appId + "\n" + timestamp + "\n" + nonceStr + "\n" + prepayId + "\n";
        
        RSASigner signer = new RSASigner(mchSerialNo, privateKey);
        String sign = signer.sign(message).getSign();

        Map<String, String> map = new HashMap<>();
        map.put("appid", appId);
        map.put("partnerid", mchId);
        map.put("prepayid", prepayId);
        map.put("package", "Sign=WXPay");
        map.put("noncestr", nonceStr);
        map.put("timestamp", String.valueOf(timestamp));
        map.put("sign", sign);
        return map;
    }

    /**
     * JSAPI/小程序 支付二次签名
     *
     * @param appId      应用ID
     * @param prepayId   预支付交易会话ID
     * @param privateKey 商户私钥
     * @return 返回给 JSAPI/小程序的参数
     */
    public static Map<String, String> signJsapi(String appId, String prepayId, PrivateKey privateKey, String mchSerialNo) {
        long timestamp = Instant.now().getEpochSecond();
        String nonceStr = UUID.randomUUID().toString().replace("-", "");
        String packageStr = "prepay_id=" + prepayId;
        String message = appId + "\n" + timestamp + "\n" + nonceStr + "\n" + packageStr + "\n";
        
        RSASigner signer = new RSASigner(mchSerialNo, privateKey);
        String sign = signer.sign(message).getSign();

        Map<String, String> map = new HashMap<>();
        map.put("appId", appId);
        map.put("timeStamp", String.valueOf(timestamp));
        map.put("nonceStr", nonceStr);
        map.put("package", packageStr);
        map.put("signType", "RSA");
        map.put("paySign", sign);
        return map;
    }
}
