package org.dromara.pay.core.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.wechat.pay.java.core.cipher.RSASigner;
import java.security.PrivateKey;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付工具类
 */
public class WechatPayUtil {

    public static Map<String, String> signApp(String appId, String mchId, String prepayId, PrivateKey privateKey, String certificateSerialNo) {
        long timestamp = Instant.now().getEpochSecond();
        String nonceStr = RandomUtil.randomString(32);
        String message = appId + "\n" + timestamp + "\n" + nonceStr + "\n" + prepayId + "\n";
        
        RSASigner signer = new RSASigner(certificateSerialNo, 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;
    }

    public static Map<String, String> signJsapi(String appId, String prepayId, PrivateKey privateKey, String certificateSerialNo) {
        long timestamp = Instant.now().getEpochSecond();
        String nonceStr = RandomUtil.randomString(32);
        String packageStr = "prepay_id=" + prepayId;
        String message = appId + "\n" + timestamp + "\n" + nonceStr + "\n" + packageStr + "\n";

        RSASigner signer = new RSASigner(certificateSerialNo, 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;
    }
}
